
var Prototype = {
 Version: '1.5.1.1',

 Browser: {
  IE:   !!(window.attachEvent && !window.opera),
  Opera: !!window.opera,
  WebKit: navigator.userAgent.indexOf('AppleWebKit/') > -1,
  Gecko: navigator.userAgent.indexOf('Gecko') > -1 && navigator.userAgent.indexOf('KHTML') == -1
 },

 BrowserFeatures: {
  XPath: !!document.evaluate,
  ElementExtensions: !!window.HTMLElement,
  SpecificElementExtensions:
   (document.createElement('div').__proto__ !==
    document.createElement('form').__proto__)
 },

 ScriptFragment: '<script[^>]*>([\\S\\s]*?)<\/script>',
 JSONFilter: /^\/\*-secure-([\s\S]*)\*\/\s*$/,

 emptyFunction: function() { },
 K: function(x) { return x }
}



var Class = {
 create: function() {
  return function() {
   this.initialize.apply(this, arguments);
  }
 }
}

var Abstract = new Object();

Object.extend = function(destination, source) {
 for (var property in source) {
  destination[property] = source[property];
 }
 return destination;
}

Object.extend(Object, {
 inspect: function(object) {
  try {
   if (object === undefined) return 'undefined';
   if (object === null) return 'null';
   return object.inspect ? object.inspect() : object.toString();
  } catch (e) {
   if (e instanceof RangeError) return '...';
   throw e;
  }
 },

 toJSON: function(object) {
  var type = typeof object;
  switch(type) {
   case 'undefined':
   case 'function':
   case 'unknown': return;
   case 'boolean': return object.toString();
  }
  if (object === null) return 'null';
  if (object.toJSON) return object.toJSON();
  if (object.ownerDocument === document) return;
  var results = [];
  for (var property in object) {
   var value = Object.toJSON(object[property]);
   if (value !== undefined)
    results.push(property.toJSON() + ': ' + value);
  }
  return '{' + results.join(', ') + '}';
 },

 keys: function(object) {
  var keys = [];
  for (var property in object)
   keys.push(property);
  return keys;
 },

 values: function(object) {
  var values = [];
  for (var property in object)
   values.push(object[property]);
  return values;
 },

 clone: function(object) {
  return Object.extend({}, object);
 }
});

Function.prototype.bind = function() {
 var __method = this, args = $A(arguments), object = args.shift();
 return function() {
  return __method.apply(object, args.concat($A(arguments)));
 }
}

Function.prototype.bindAsEventListener = function(object) {
 var __method = this, args = $A(arguments), object = args.shift();
 return function(event) {
  return __method.apply(object, [event || window.event].concat(args));
 }
}

Object.extend(Number.prototype, {
 toColorPart: function() {
  return this.toPaddedString(2, 16);
 },

 succ: function() {
  return this + 1;
 },

 times: function(iterator) {
  $R(0, this, true).each(iterator);
  return this;
 },

 toPaddedString: function(length, radix) {
  var string = this.toString(radix || 10);
  return '0'.times(length - string.length) + string;
 },

 toJSON: function() {
  return isFinite(this) ? this.toString() : 'null';
 }
});

Date.prototype.toJSON = function() {
 return '"' + this.getFullYear() + '-' +
  (this.getMonth() + 1).toPaddedString(2) + '-' +
  this.getDate().toPaddedString(2) + 'T' +
  this.getHours().toPaddedString(2) + ':' +
  this.getMinutes().toPaddedString(2) + ':' +
  this.getSeconds().toPaddedString(2) + '"';
};

var Try = {
 these: function() {
  var returnValue;

  for (var i = 0, length = arguments.length; i < length; i++) {
   var lambda = arguments[i];
   try {
    returnValue = lambda();
    break;
   } catch (e) {}
  }

  return returnValue;
 }
}


var PeriodicalExecuter = Class.create();
PeriodicalExecuter.prototype = {
 initialize: function(callback, frequency) {
  this.callback = callback;
  this.frequency = frequency;
  this.currentlyExecuting = false;

  this.registerCallback();
 },

 registerCallback: function() {
  this.timer = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
 },

 stop: function() {
  if (!this.timer) return;
  clearInterval(this.timer);
  this.timer = null;
 },

 onTimerEvent: function() {
  if (!this.currentlyExecuting) {
   try {
    this.currentlyExecuting = true;
    this.callback(this);
   } finally {
    this.currentlyExecuting = false;
   }
  }
 }
}
Object.extend(String, {
 interpret: function(value) {
  return value == null ? '' : String(value);
 },
 specialChar: {
  '\b': '\\b',
  '\t': '\\t',
  '\n': '\\n',
  '\f': '\\f',
  '\r': '\\r',
  '\\': '\\\\'
 }
});

Object.extend(String.prototype, {
 gsub: function(pattern, replacement) {
  var result = '', source = this, match;
  replacement = arguments.callee.prepareReplacement(replacement);

  while (source.length > 0) {
   if (match = source.match(pattern)) {
    result += source.slice(0, match.index);
    result += String.interpret(replacement(match));
    source = source.slice(match.index + match[0].length);
   } else {
    result += source, source = '';
   }
  }
  return result;
 },

 sub: function(pattern, replacement, count) {
  replacement = this.gsub.prepareReplacement(replacement);
  count = count === undefined ? 1 : count;

  return this.gsub(pattern, function(match) {
   if (--count < 0) return match[0];
   return replacement(match);
  });
 },

 scan: function(pattern, iterator) {
  this.gsub(pattern, iterator);
  return this;
 },

 truncate: function(length, truncation) {
  length = length || 30;
  truncation = truncation === undefined ? '...' : truncation;
  return this.length > length ?
   this.slice(0, length - truncation.length) + truncation : this;
 },

 strip: function() {
  return this.replace(/^\s+/, '').replace(/\s+$/, '');
 },

 stripTags: function() {
  return this.replace(/<\/?[^>]+>/gi, '');
 },

 stripScripts: function() {
  return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), '');
 },

 extractScripts: function() {
  var matchAll = new RegExp(Prototype.ScriptFragment, 'img');
  var matchOne = new RegExp(Prototype.ScriptFragment, 'im');
  return (this.match(matchAll) || []).map(function(scriptTag) {
   return (scriptTag.match(matchOne) || ['', ''])[1];
  });
 },

 evalScripts: function() {
  return this.extractScripts().map(function(script) { return eval(script) });
 },

 escapeHTML: function() {
  var self = arguments.callee;
  self.text.data = this;
  return self.div.innerHTML;
 },

 unescapeHTML: function() {
  var div = document.createElement('div');
  div.innerHTML = this.stripTags();
  return div.childNodes[0] ? (div.childNodes.length > 1 ?
   $A(div.childNodes).inject('', function(memo, node) { return memo+node.nodeValue }) :
   div.childNodes[0].nodeValue) : '';
 },

 toQueryParams: function(separator) {
  var match = this.strip().match(/([^?#]*)(#.*)?$/);
  if (!match) return {};

  return match[1].split(separator || '&').inject({}, function(hash, pair) {
   if ((pair = pair.split('='))[0]) {
    var key = decodeURIComponent(pair.shift());
    var value = pair.length > 1 ? pair.join('=') : pair[0];
    if (value != undefined) value = decodeURIComponent(value);

    if (key in hash) {
     if (hash[key].constructor != Array) hash[key] = [hash[key]];
     hash[key].push(value);
    }
    else hash[key] = value;
   }
   return hash;
  });
 },

 toArray: function() {
  return this.split('');
 },

 succ: function() {
  return this.slice(0, this.length - 1) +
   String.fromCharCode(this.charCodeAt(this.length - 1) + 1);
 },

 times: function(count) {
  var result = '';
  for (var i = 0; i < count; i++) result += this;
  return result;
 },

 camelize: function() {
  var parts = this.split('-'), len = parts.length;
  if (len == 1) return parts[0];

  var camelized = this.charAt(0) == '-'
   ? parts[0].charAt(0).toUpperCase() + parts[0].substring(1)
   : parts[0];

  for (var i = 1; i < len; i++)
   camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1);

  return camelized;
 },

 capitalize: function() {
  return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase();
 },

 underscore: function() {
  return this.gsub(/::/, '/').gsub(/([A-Z]+)([A-Z][a-z])/,'#{1}_#{2}').gsub(/([a-z\d])([A-Z])/,'#{1}_#{2}').gsub(/-/,'_').toLowerCase();
 },

 dasherize: function() {
  return this.gsub(/_/,'-');
 },

 inspect: function(useDoubleQuotes) {
  var escapedString = this.gsub(/[\x00-\x1f\\]/, function(match) {
   var character = String.specialChar[match[0]];
   return character ? character : '\\u00' + match[0].charCodeAt().toPaddedString(2, 16);
  });
  if (useDoubleQuotes) return '"' + escapedString.replace(/"/g, '\\"') + '"';
  return "'" + escapedString.replace(/'/g, '\\\'') + "'";
 },

 toJSON: function() {
  return this.inspect(true);
 },

 unfilterJSON: function(filter) {
  return this.sub(filter || Prototype.JSONFilter, '#{1}');
 },

 isJSON: function() {
  var str = this.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, '');
  return (/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(str);
 },

 evalJSON: function(sanitize) {
  var json = this.unfilterJSON();
  try {
   if (!sanitize || json.isJSON()) return eval('(' + json + ')');
  } catch (e) { }
  throw new SyntaxError('Badly formed JSON string: ' + this.inspect());
 },

 include: function(pattern) {
  return this.indexOf(pattern) > -1;
 },

 startsWith: function(pattern) {
  return this.indexOf(pattern) === 0;
 },

 endsWith: function(pattern) {
  var d = this.length - pattern.length;
  return d >= 0 && this.lastIndexOf(pattern) === d;
 },

 empty: function() {
  return this == '';
 },

 blank: function() {
  return /^\s*$/.test(this);
 }
});



if (Prototype.Browser.WebKit || Prototype.Browser.IE) Object.extend(String.prototype, {
 escapeHTML: function() {
  return this.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
 },
 unescapeHTML: function() {
  return this.replace(/&amp;/g,'&').replace(/&lt;/g,'<').replace(/&gt;/g,'>');
 }
});

String.prototype.gsub.prepareReplacement = function(replacement) {
 if (typeof replacement == 'function') return replacement;
 var template = new Template(replacement);
 return function(match) { return template.evaluate(match) };
}

String.prototype.parseQuery = String.prototype.toQueryParams;

Object.extend(String.prototype.escapeHTML, {
 div: document.createElement('div'),
 text: document.createTextNode('')
});

with (String.prototype.escapeHTML) div.appendChild(text);

var Template = Class.create();
Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/;
Template.prototype = {
 initialize: function(template, pattern) {
  this.template = template.toString();
  this.pattern = pattern || Template.Pattern;
 },

 evaluate: function(object) {
  return this.template.gsub(this.pattern, function(match) {
   var before = match[1];
   if (before == '\\') return match[2];
   return before + String.interpret(object[match[3]]);
  });
 }
}

var $break = {}, $continue = new Error('"throw $continue" is deprecated, use "return" instead');

var Enumerable = {
 each: function(iterator) {
  var index = 0;var e;
  try {
   this._each(function(value) {
    iterator(value, index++);
   });
  }catch(e){
  
  //LINHA MODIFICADA	 INSERI TRY
  
   try { if (e != $break) throw e; }catch(eE){}
  }
  return this;
 },

 eachSlice: function(number, iterator) {
  var index = -number, slices = [], array = this.toArray();
  while ((index += number) < array.length)




   slices.push(array.slice(index, index+number));
  return slices.map(iterator);
 },

 all: function(iterator) {
  var result = true;
  this.each(function(value, index) {
   result = result && !!(iterator || Prototype.K)(value, index);
   if (!result) throw $break;
  });
  return result;
 },

 any: function(iterator) {
  var result = false;
  this.each(function(value, index) {
   if (result = !!(iterator || Prototype.K)(value, index))
    throw $break;
  });
  return result;
 },

 collect: function(iterator) {
  var results = [];
  this.each(function(value, index) {
   results.push((iterator || Prototype.K)(value, index));
  });
  return results;
 },

 detect: function(iterator) {
  var result;
  this.each(function(value, index) {
   if (iterator(value, index)) {
    result = value;
    throw $break;
   }
  });
  return result;
 },

 findAll: function(iterator) {
  var results = [];
  this.each(function(value, index) {
   if (iterator(value, index))
    results.push(value);
  });
  return results;
 },

 grep: function(pattern, iterator) {
  var results = [];
  this.each(function(value, index) {
   var stringValue = value.toString();
   if (stringValue.match(pattern))
    results.push((iterator || Prototype.K)(value, index));
  })
  return results;
 },

 include: function(object) {
  var found = false;
  this.each(function(value) {
   if (value == object) {
    found = true;
    throw $break;
   }
  });
  return found;
 },

 inGroupsOf: function(number, fillWith) {
  fillWith = fillWith === undefined ? null : fillWith;
  return this.eachSlice(number, function(slice) {
   while(slice.length < number) slice.push(fillWith);
   return slice;
  });
 },

 inject: function(memo, iterator) {
  this.each(function(value, index) {
   memo = iterator(memo, value, index);
  });
  return memo;
 },

 invoke: function(method) {
  var args = $A(arguments).slice(1);
  return this.map(function(value) {
   return value[method].apply(value, args);
  });
 },

 max: function(iterator) {
  var result;
  this.each(function(value, index) {
   value = (iterator || Prototype.K)(value, index);
   if (result == undefined || value >= result)
    result = value;
  });
  return result;
 },

 min: function(iterator) {
  var result;
  this.each(function(value, index) {
   value = (iterator || Prototype.K)(value, index);
   if (result == undefined || value < result)
    result = value;
  });
  return result;
 },

 partition: function(iterator) {
  var trues = [], falses = [];
  this.each(function(value, index) {
   ((iterator || Prototype.K)(value, index) ?
    trues : falses).push(value);
  });
  return [trues, falses];
 },

 pluck: function(property) {
  var results = [];
  this.each(function(value, index) {
   results.push(value[property]);
  });
  return results;
 },

 reject: function(iterator) {
  var results = [];
  this.each(function(value, index) {
   if (!iterator(value, index))
    results.push(value);
  });
  return results;
 },

 sortBy: function(iterator) {
  return this.map(function(value, index) {
   return {value: value, criteria: iterator(value, index)};
  }).sort(function(left, right) {
   var a = left.criteria, b = right.criteria;
   return a < b ? -1 : a > b ? 1 : 0;
  }).pluck('value');
 },

 toArray: function() {
  return this.map();
 },

 zip: function() {
  var iterator = Prototype.K, args = $A(arguments);
  if (typeof args.last() == 'function')
   iterator = args.pop();

  var collections = [this].concat(args).map($A);
  return this.map(function(value, index) {
   return iterator(collections.pluck(index));
  });
 },

 size: function() {
  return this.toArray().length;
 },

 inspect: function() {
  return '#<Enumerable:' + this.toArray().inspect() + '>';
 }
}

Object.extend(Enumerable, {
 map:   Enumerable.collect,
 find:  Enumerable.detect,
 select: Enumerable.findAll,
 member: Enumerable.include,
 entries: Enumerable.toArray
});
var $A = Array.from = function(iterable) {
 if (!iterable) return [];
 if (iterable.toArray) {
  return iterable.toArray();
 } else {
  var results = [];
  for (var i = 0, length = iterable.length; i < length; i++)
   results.push(iterable[i]);
  return results;
 }
}

if (Prototype.Browser.WebKit) {
 $A = Array.from = function(iterable) {
  if (!iterable) return [];
  if (!(typeof iterable == 'function' && iterable == '[object NodeList]') &&
   iterable.toArray) {
   return iterable.toArray();
  } else {
   var results = [];
   for (var i = 0, length = iterable.length; i < length; i++)
    results.push(iterable[i]);
   return results;
  }
 }
}

Object.extend(Array.prototype, Enumerable);

if (!Array.prototype._reverse)
 Array.prototype._reverse = Array.prototype.reverse;

Object.extend(Array.prototype, {
 _each: function(iterator) {
  for (var i = 0, length = this.length; i < length; i++)
   iterator(this[i]);
 },

 clear: function() {
  this.length = 0;
  return this;
 },

 first: function() {
  return this[0];
 },

 last: function() {
  return this[this.length - 1];
 },

 compact: function() {
  return this.select(function(value) {
   return value != null;
  });
 },

 flatten: function() {
  return this.inject([], function(array, value) {
   return array.concat(value && value.constructor == Array ?
    value.flatten() : [value]);
  });
 },

 without: function() {
  var values = $A(arguments);
  return this.select(function(value) {
   return !values.include(value);
  });
 },

 indexOf: function(object) {
  for (var i = 0, length = this.length; i < length; i++)
   if (this[i] == object) return i;
  return -1;
 },

 reverse: function(inline) {
  return (inline !== false ? this : this.toArray())._reverse();
 },

 reduce: function() {
  return this.length > 1 ? this : this[0];
 },

 uniq: function(sorted) {
  return this.inject([], function(array, value, index) {
   if (0 == index || (sorted ? array.last() != value : !array.include(value)))
    array.push(value);
   return array;
  });
 },

 clone: function() {
  return [].concat(this);
 },

 size: function() {
  return this.length;
 },

 inspect: function() {
  return '[' + this.map(Object.inspect).join(', ') + ']';
 },

 toJSON: function() {
  var results = [];
  this.each(function(object) {
   var value = Object.toJSON(object);
   if (value !== undefined) results.push(value);
  });
  return '[' + results.join(', ') + ']';
 }
});

Array.prototype.toArray = Array.prototype.clone;

function $w(string) {
 string = string.strip();
 return string ? string.split(/\s+/) : [];
}

if (Prototype.Browser.Opera){
 Array.prototype.concat = function() {
  var array = [];
  for (var i = 0, length = this.length; i < length; i++) array.push(this[i]);
  for (var i = 0, length = arguments.length; i < length; i++) {
   if (arguments[i].constructor == Array) {
    for (var j = 0, arrayLength = arguments[i].length; j < arrayLength; j++)
     array.push(arguments[i][j]);
   } else {
    array.push(arguments[i]);
   }
  }
  return array;
 }
}
var Hash = function(object) {
 if (object instanceof Hash) this.merge(object);
 else Object.extend(this, object || {});
};

Object.extend(Hash, {
 toQueryString: function(obj) {
  var parts = [];
  parts.add = arguments.callee.addPair;

  this.prototype._each.call(obj, function(pair) {
   if (!pair.key) return;
   var value = pair.value;

   if (value && typeof value == 'object') {
    if (value.constructor == Array) value.each(function(value) {
     parts.add(pair.key, value);
    });
    return;
   }
   parts.add(pair.key, value);
  });

  return parts.join('&');
 },

 toJSON: function(object) {
  var results = [];
  this.prototype._each.call(object, function(pair) {
   var value = Object.toJSON(pair.value);
   if (value !== undefined) results.push(pair.key.toJSON() + ': ' + value);
  });
  return '{' + results.join(', ') + '}';
 }
});

Hash.toQueryString.addPair = function(key, value, prefix) {
 key = encodeURIComponent(key);
 if (value === undefined) this.push(key);
 else this.push(key + '=' + (value == null ? '' : encodeURIComponent(value)));
}

Object.extend(Hash.prototype, Enumerable);
Object.extend(Hash.prototype, {
 _each: function(iterator) {
  for (var key in this) {
   var value = this[key];
   if (value && value == Hash.prototype[key]) continue;

   var pair = [key, value];
   pair.key = key;
   pair.value = value;
   iterator(pair);
  }
 },

 keys: function() {
  return this.pluck('key');
 },

 values: function() {
  return this.pluck('value');
 },

 merge: function(hash) {
  return $H(hash).inject(this, function(mergedHash, pair) {
   mergedHash[pair.key] = pair.value;
   return mergedHash;
  });
 },

 remove: function() {
  var result;
  for(var i = 0, length = arguments.length; i < length; i++) {
   var value = this[arguments[i]];
   if (value !== undefined){
    if (result === undefined) result = value;
    else {
     if (result.constructor != Array) result = [result];
     result.push(value)
    }
   }
   delete this[arguments[i]];
  }
  return result;
 },

 toQueryString: function() {
  return Hash.toQueryString(this);
 },

 inspect: function() {
  return '#<Hash:{' + this.map(function(pair) {
   return pair.map(Object.inspect).join(': ');
  }).join(', ') + '}>';
 },

 toJSON: function() {
  return Hash.toJSON(this);
 }
});

function $H(object) {
 if (object instanceof Hash) return object;
 return new Hash(object);
};

if (function() {
 var i = 0, Test = function(value) { this.key = value };
 Test.prototype.key = 'foo';
 for (var property in new Test('bar')) i++;
 return i > 1;
}()) Hash.prototype._each = function(iterator) {
 var cache = [];
 for (var key in this) {
  var value = this[key];
  if ((value && value == Hash.prototype[key]) || cache.include(key)) continue;
  cache.push(key);
  var pair = [key, value];
  pair.key = key;
  pair.value = value;
  iterator(pair);
 }
};
ObjectRange = Class.create();
Object.extend(ObjectRange.prototype, Enumerable);
Object.extend(ObjectRange.prototype, {
 initialize: function(start, end, exclusive) {
  this.start = start;
  this.end = end;
  this.exclusive = exclusive;
 },

 _each: function(iterator) {
  var value = this.start;
  while (this.include(value)) {
   iterator(value);
   value = value.succ();
  }
 },

 include: function(value) {
  if (value < this.start)
   return false;
  if (this.exclusive)
   return value < this.end;
  return value <= this.end;
 }
});

var $R = function(start, end, exclusive) {
 return new ObjectRange(start, end, exclusive);
}

var Ajax = {
 getTransport: function() {
  return Try.these(
   function() {return new XMLHttpRequest()},
   function() {return new ActiveXObject('Msxml2.XMLHTTP')},
   function() {return new ActiveXObject('Microsoft.XMLHTTP')}
  ) || false;
 },

 activeRequestCount: 0
}

Ajax.Responders = {
 responders: [],

 _each: function(iterator) {
  this.responders._each(iterator);
 },

 register: function(responder) {
  if (!this.include(responder))
   this.responders.push(responder);
 },

 unregister: function(responder) {
  this.responders = this.responders.without(responder);
 },

 dispatch: function(callback, request, transport, json) {
  this.each(function(responder) {
   if (typeof responder[callback] == 'function') {
    try {
     responder[callback].apply(responder, [request, transport, json]);
    } catch (e) {}
   }
  });
 }
};

Object.extend(Ajax.Responders, Enumerable);

Ajax.Responders.register({
 onCreate: function() {
  Ajax.activeRequestCount++;
 },
 onComplete: function() {
  Ajax.activeRequestCount--;
 }
});

Ajax.Base = function() {};
Ajax.Base.prototype = {
 setOptions: function(options) {
  this.options = {
   method:    'post',
   asynchronous: true,
   contentType: 'application/x-www-form-urlencoded',
   encoding:   'UTF-8',
   parameters:  ''
  }
  Object.extend(this.options, options || {});

  this.options.method = this.options.method.toLowerCase();
  if (typeof this.options.parameters == 'string')
   this.options.parameters = this.options.parameters.toQueryParams();
 }
}

Ajax.Request = Class.create();
Ajax.Request.Events =
 ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete'];

Ajax.Request.prototype = Object.extend(new Ajax.Base(), {
 _complete: false,

 initialize: function(url, options) {
  this.transport = Ajax.getTransport();
  this.setOptions(options);
  this.request(url);
 },

 request: function(url) {
  this.url = url;
  this.method = this.options.method;
  var params = Object.clone(this.options.parameters);

  if (!['get', 'post'].include(this.method)) {
   
   params['_method'] = this.method;
   this.method = 'post';
  }

  this.parameters = params;

  if (params = Hash.toQueryString(params)) {
   
   if (this.method == 'get')
    this.url += (this.url.include('?') ? '&' : '?') + params;
   else if (/Konqueror|Safari|KHTML/.test(navigator.userAgent))
    params += '&_=';
  }

  try {
   if (this.options.onCreate) this.options.onCreate(this.transport);
   Ajax.Responders.dispatch('onCreate', this, this.transport);

   this.transport.open(this.method.toUpperCase(), this.url,
    this.options.asynchronous);

   if (this.options.asynchronous)
    setTimeout(function() { this.respondToReadyState(1) }.bind(this), 10);

   this.transport.onreadystatechange = this.onStateChange.bind(this);
   this.setRequestHeaders();

   this.body = this.method == 'post' ? (this.options.postBody || params) : null;
   this.transport.send(this.body);

   /* Force Firefox to handle ready state 4 for synchronous requests */
   if (!this.options.asynchronous && this.transport.overrideMimeType)
    this.onStateChange();

  }
  catch (e) {
   this.dispatchException(e);
  }
 },

 onStateChange: function() {
  var readyState = this.transport.readyState;
  if (readyState > 1 && !((readyState == 4) && this._complete))
   this.respondToReadyState(this.transport.readyState);
 },

 setRequestHeaders: function() {
  var headers = {
   'X-Requested-With': 'XMLHttpRequest',
   'X-Prototype-Version': Prototype.Version,
   'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
  };

  if (this.method == 'post') {
   headers['Content-type'] = this.options.contentType +
    (this.options.encoding ? '; charset=' + this.options.encoding : '');

   /* Force "Connection: close" for older Mozilla browsers to work
    * around a bug where XMLHttpRequest sends an incorrect
    * Content-length header. See Mozilla Bugzilla #246651.
    */
   if (this.transport.overrideMimeType &&
     (navigator.userAgent.match(/Gecko\/(\d{4})/) || [0,2005])[1] < 2005)
      headers['Connection'] = 'close';
  }

 
  if (typeof this.options.requestHeaders == 'object') {
   var extras = this.options.requestHeaders;

   if (typeof extras.push == 'function')
    for (var i = 0, length = extras.length; i < length; i += 2)
     headers[extras[i]] = extras[i+1];
   else
    $H(extras).each(function(pair) { headers[pair.key] = pair.value });
  }

  for (var name in headers)
   this.transport.setRequestHeader(name, headers[name]);
 },

 success: function() {
  return !this.transport.status
    || (this.transport.status >= 200 && this.transport.status < 300);
 },

 respondToReadyState: function(readyState) {
  var state = Ajax.Request.Events[readyState];
  var transport = this.transport, json = this.evalJSON();

  if (state == 'Complete') {
   try {
    this._complete = true;
    (this.options['on' + this.transport.status]
     || this.options['on' + (this.success() ? 'Success' : 'Failure')]
     || Prototype.emptyFunction)(transport, json);
   } catch (e) {
    this.dispatchException(e);
   }

   var contentType = this.getHeader('Content-type');
   if (contentType && contentType.strip().
    match(/^(text|application)\/(x-)?(java|ecma)script(;.*)?$/i))
     this.evalResponse();
  }

  try {
   (this.options['on' + state] || Prototype.emptyFunction)(transport, json);
   Ajax.Responders.dispatch('on' + state, this, transport, json);
  } catch (e) {
   this.dispatchException(e);
  }

  if (state == 'Complete') {
   
   this.transport.onreadystatechange = Prototype.emptyFunction;
  }
 },

 getHeader: function(name) {
  try {
   return this.transport.getResponseHeader(name);
  } catch (e) { return null }
 },

 evalJSON: function() {
  try {
   var json = this.getHeader('X-JSON');
   return json ? json.evalJSON() : null;
  } catch (e) { return null }
 },

 evalResponse: function() {
  try {
   return eval((this.transport.responseText || '').unfilterJSON());
  } catch (e) {
   this.dispatchException(e);
  }
 },

 dispatchException: function(exception) {
  (this.options.onException || Prototype.emptyFunction)(this, exception);
  Ajax.Responders.dispatch('onException', this, exception);
 }
});





Ajax.Updater = Class.create();

Object.extend(Object.extend(Ajax.Updater.prototype, Ajax.Request.prototype), {
 initialize: function(container, url, options) {
  this.container = {
   success: (container.success || container),
   failure: (container.failure || (container.success ? null : container))
  }

  this.transport = Ajax.getTransport();
  this.setOptions(options);

  var onComplete = this.options.onComplete || Prototype.emptyFunction;
  this.options.onComplete = (function(transport, param) {
   this.updateContent();
   onComplete(transport, param);
  }).bind(this);

  this.request(url);
 },

 updateContent: function() {
  var receiver = this.container[this.success() ? 'success' : 'failure'];
  var response = this.transport.responseText;

  if (!this.options.evalScripts) response = response.stripScripts();

  if (receiver = $(receiver)) {
   if (this.options.insertion)
    new this.options.insertion(receiver, response);
   else
    receiver.update(response);
  }

  if (this.success()) {
   if (this.onComplete)
    setTimeout(this.onComplete.bind(this), 10);
  }
 }
});

Ajax.PeriodicalUpdater = Class.create();
Ajax.PeriodicalUpdater.prototype = Object.extend(new Ajax.Base(), {
 initialize: function(container, url, options) {
  this.setOptions(options);
  this.onComplete = this.options.onComplete;

  this.frequency = (this.options.frequency || 2);
  this.decay = (this.options.decay || 1);

  this.updater = {};
  this.container = container;
  this.url = url;

  this.start();
 },

 start: function() {
  this.options.onComplete = this.updateComplete.bind(this);
  this.onTimerEvent();
 },

 stop: function() {
  this.updater.options.onComplete = undefined;
  clearTimeout(this.timer);
  (this.onComplete || Prototype.emptyFunction).apply(this, arguments);
 },

 updateComplete: function(request) {
  if (this.options.decay) {
   this.decay = (request.responseText == this.lastText ?
    this.decay * this.options.decay : 1);

   this.lastText = request.responseText;
  }
	
	
	
	
	
	
	// PHANTON EFFECT'S BUG FIXED 
	
	
	
	
	
  //this.timer = setTimeout(this.onTimerEvent.bind(this),
   // this.decay * this.frequency * 1000);
 },

 onTimerEvent: function() {
  this.updater = new Ajax.Updater(this.container, this.url, this.options);
 }
});
function $(element) {
 if (arguments.length > 1) {
  for (var i = 0, elements = [], length = arguments.length; i < length; i++)
   elements.push($(arguments[i]));
  return elements;
 }
 if (typeof element == 'string')
  element = document.getElementById(element);
 return Element.extend(element);
}



if (Prototype.BrowserFeatures.XPath) {
 document._getElementsByXPath = function(expression, parentElement) {
  var results = [];
  var query = document.evaluate(expression, $(parentElement) || document,
   null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
  for (var i = 0, length = query.snapshotLength; i < length; i++)
   results.push(query.snapshotItem(i));
  return results;
 };

 document.getElementsByClassName = function(className, parentElement) {
  var q = ".//*[contains(concat(' ', @class, ' '), ' " + className + " ')]";
  return document._getElementsByXPath(q, parentElement);
 }

} else document.getElementsByClassName = function(className, parentElement) {
 var children = ($(parentElement) || document.body).getElementsByTagName('*');
 var elements = [], child, pattern = new RegExp("(^|\\s)" + className + "(\\s|$)");
 for (var i = 0, length = children.length; i < length; i++) {
  child = children[i];
  var elementClassName = child.className;
  if (elementClassName.length == 0) continue;
  if (elementClassName == className || elementClassName.match(pattern))
   elements.push(Element.extend(child));
 }
 return elements;
};




if (!window.Element) var Element = {};

Element.extend = function(element) {
 var F = Prototype.BrowserFeatures;
 if (!element || !element.tagName || element.nodeType == 3 ||
  element._extended || F.SpecificElementExtensions || element == window)
  return element;

 var methods = {}, tagName = element.tagName, cache = Element.extend.cache,
  T = Element.Methods.ByTag;

 
 if (!F.ElementExtensions) {
  Object.extend(methods, Element.Methods),
  Object.extend(methods, Element.Methods.Simulated);
 }

 
 if (T[tagName]) Object.extend(methods, T[tagName]);

 for (var property in methods) {
  var value = methods[property];
  if (typeof value == 'function' && !(property in element))
   element[property] = cache.findOrStore(value);
 }

 element._extended = Prototype.emptyFunction;
 return element;
};

Element.extend.cache = {
 findOrStore: function(value) {
  return this[value] = this[value] || function() {
   return value.apply(null, [this].concat($A(arguments)));
  }
 }
};

Element.Methods = {
 visible: function(element) {
  return $(element).style.display != 'none';
 },

 toggle: function(element) {
  element = $(element);
  Element[Element.visible(element) ? 'hide' : 'show'](element);
  return element;
 },

 hide: function(element) {
  $(element).style.display = 'none';
  return element;
 },

 show: function(element) {
  $(element).style.display = '';
  return element;
 },

 remove: function(element) {
  element = $(element);
  element.parentNode.removeChild(element);
  return element;
 },

 update: function(element, html) {
  html = typeof html == 'undefined' ? '' : html.toString();
  $(element).innerHTML = html.stripScripts();
  setTimeout(function() {html.evalScripts()}, 10);
  return element;
 },

 replace: function(element, html) {
  element = $(element);
  html = typeof html == 'undefined' ? '' : html.toString();
  if (element.outerHTML) {
   element.outerHTML = html.stripScripts();
  } else {
   var range = element.ownerDocument.createRange();
   range.selectNodeContents(element);
   element.parentNode.replaceChild(
    range.createContextualFragment(html.stripScripts()), element);
  }
  setTimeout(function() {html.evalScripts()}, 10);
  return element;
 },

 inspect: function(element) {
  element = $(element);
  var result = '<' + element.tagName.toLowerCase();
  $H({'id': 'id', 'className': 'class'}).each(function(pair) {
   var property = pair.first(), attribute = pair.last();
   var value = (element[property] || '').toString();
   if (value) result += ' ' + attribute + '=' + value.inspect(true);
  });
  return result + '>';
 },

 recursivelyCollect: function(element, property) {
  element = $(element);
  var elements = [];
  while (element = element[property])
   if (element.nodeType == 1)
    elements.push(Element.extend(element));
  return elements;
 },

 ancestors: function(element) {
  return $(element).recursivelyCollect('parentNode');
 },

 descendants: function(element) {
  return $A($(element).getElementsByTagName('*')).each(Element.extend);
 },

 firstDescendant: function(element) {
  element = $(element).firstChild;
  while (element && element.nodeType != 1) element = element.nextSibling;
  return $(element);
 },

 immediateDescendants: function(element) {
  if (!(element = $(element).firstChild)) return [];
  while (element && element.nodeType != 1) element = element.nextSibling;
  if (element) return [element].concat($(element).nextSiblings());
  return [];
 },

 previousSiblings: function(element) {
  return $(element).recursivelyCollect('previousSibling');
 },

 nextSiblings: function(element) {
  return $(element).recursivelyCollect('nextSibling');
 },

 siblings: function(element) {
  element = $(element);
  return element.previousSiblings().reverse().concat(element.nextSiblings());
 },

 match: function(element, selector) {
  if (typeof selector == 'string')
   selector = new Selector(selector);
  return selector.match($(element));
 },

 up: function(element, expression, index) {
  element = $(element);
  if (arguments.length == 1) return $(element.parentNode);
  var ancestors = element.ancestors();
  return expression ? Selector.findElement(ancestors, expression, index) :
   ancestors[index || 0];
 },

 down: function(element, expression, index) {
  element = $(element);
  if (arguments.length == 1) return element.firstDescendant();
  var descendants = element.descendants();
  return expression ? Selector.findElement(descendants, expression, index) :
   descendants[index || 0];
 },

 previous: function(element, expression, index) {
  element = $(element);
  if (arguments.length == 1) return $(Selector.handlers.previousElementSibling(element));
  var previousSiblings = element.previousSiblings();
  return expression ? Selector.findElement(previousSiblings, expression, index) :
   previousSiblings[index || 0];
 },

 next: function(element, expression, index) {
  element = $(element);
  if (arguments.length == 1) return $(Selector.handlers.nextElementSibling(element));
  var nextSiblings = element.nextSiblings();
  return expression ? Selector.findElement(nextSiblings, expression, index) :
   nextSiblings[index || 0];
 },

 getElementsBySelector: function() {
  var args = $A(arguments), element = $(args.shift());
  return Selector.findChildElements(element, args);
 },

 getElementsByClassName: function(element, className) {
  return document.getElementsByClassName(className, element);
 },

 readAttribute: function(element, name) {
  element = $(element);
  if (Prototype.Browser.IE) {
   if (!element.attributes) return null;
   var t = Element._attributeTranslations;
   if (t.values[name]) return t.values[name](element, name);
   if (t.names[name]) name = t.names[name];
   var attribute = element.attributes[name];
   return attribute ? attribute.nodeValue : null;
  }
  return element.getAttribute(name);
 },

 getHeight: function(element) {
  return $(element).getDimensions().height;
 },

 getWidth: function(element) {
  return $(element).getDimensions().width;
 },

 classNames: function(element) {
  return new Element.ClassNames(element);
 },

 hasClassName: function(element, className) {
  if (!(element = $(element))) return;
  var elementClassName = element.className;
  if (elementClassName.length == 0) return false;
  if (elementClassName == className ||
    elementClassName.match(new RegExp("(^|\\s)" + className + "(\\s|$)")))
   return true;
  return false;
 },

 addClassName: function(element, className) {
  if (!(element = $(element))) return;
  Element.classNames(element).add(className);
  return element;
 },

 removeClassName: function(element, className) {
  if (!(element = $(element))) return;
  Element.classNames(element).remove(className);
  return element;
 },

 toggleClassName: function(element, className) {
  if (!(element = $(element))) return;
  Element.classNames(element)[element.hasClassName(className) ? 'remove' : 'add'](className);
  return element;
 },

 observe: function() {
  Event.observe.apply(Event, arguments);
  return $A(arguments).first();
 },

 stopObserving: function() {
  Event.stopObserving.apply(Event, arguments);
  return $A(arguments).first();
 },


 cleanWhitespace: function(element) {
  element = $(element);
  var node = element.firstChild;
  while (node) {
   var nextNode = node.nextSibling;
   if (node.nodeType == 3 && !/\S/.test(node.nodeValue))
    element.removeChild(node);
   node = nextNode;
  }
  return element;
 },

 empty: function(element) {
  return $(element).innerHTML.blank();
 },

 descendantOf: function(element, ancestor) {
  element = $(element), ancestor = $(ancestor);
  while (element = element.parentNode)
   if (element == ancestor) return true;
  return false;
 },

 scrollTo: function(element) {
  element = $(element);
  var pos = Position.cumulativeOffset(element);
  window.scrollTo(pos[0], pos[1]);
  return element;
 },

 getStyle: function(element, style) {
  element = $(element);
  style = style == 'float' ? 'cssFloat' : style.camelize();
  var value = element.style[style];
  if (!value) {
   var css = document.defaultView.getComputedStyle(element, null);
   value = css ? css[style] : null;
  }
  if (style == 'opacity') return value ? parseFloat(value) : 1.0;
  return value == 'auto' ? null : value;
 },

 getOpacity: function(element) {
  return $(element).getStyle('opacity');
 },

 setStyle: function(element, styles, camelized) {
  element = $(element);
  var elementStyle = element.style;

  for (var property in styles)
   if (property == 'opacity') element.setOpacity(styles[property])
   else
    elementStyle[(property == 'float' || property == 'cssFloat') ?
     (elementStyle.styleFloat === undefined ? 'cssFloat' : 'styleFloat') :
     (camelized ? property : property.camelize())] = styles[property];

  return element;
 },

 setOpacity: function(element, value) {
  element = $(element);
  element.style.opacity = (value == 1 || value === '') ? '' :
   (value < 0.00001) ? 0 : value;
  return element;
 },

 getDimensions: function(element) {
  element = $(element);
  var display = $(element).getStyle('display');
  if (display != 'none' && display != null) 
   return {width: element.offsetWidth, height: element.offsetHeight};


  var els = element.style;
  var originalVisibility = els.visibility;
  var originalPosition = els.position;
  var originalDisplay = els.display;
  els.visibility = 'hidden';
  els.position = 'absolute';
  els.display = 'block';
  var originalWidth = element.clientWidth;
  var originalHeight = element.clientHeight;
  els.display = originalDisplay;
  els.position = originalPosition;
  els.visibility = originalVisibility;
  return {width: originalWidth, height: originalHeight};
 },

 makePositioned: function(element) {
  element = $(element);
  var pos = Element.getStyle(element, 'position');
  if (pos == 'static' || !pos) {
   element._madePositioned = true;
   element.style.position = 'relative';

   if (window.opera) {
    element.style.top = 0;
    element.style.left = 0;
   }
  }
  return element;
 },

 undoPositioned: function(element) {
  element = $(element);
  if (element._madePositioned) {
   element._madePositioned = undefined;
   element.style.position =
    element.style.top =
    element.style.left =
    element.style.bottom =
    element.style.right = '';
  }
  return element;
 },

 makeClipping: function(element) {
  element = $(element);
  if (element._overflow) return element;
  element._overflow = element.style.overflow || 'auto';
  if ((Element.getStyle(element, 'overflow') || 'visible') != 'hidden')
   element.style.overflow = 'hidden';
  return element;
 },

 undoClipping: function(element) {
  element = $(element);
  if (!element._overflow) return element;
  element.style.overflow = element._overflow == 'auto' ? '' : element._overflow;
  element._overflow = null;
  return element;
 }
};

Object.extend(Element.Methods, {
 childOf: Element.Methods.descendantOf,
 childElements: Element.Methods.immediateDescendants
});

if (Prototype.Browser.Opera) {
 Element.Methods._getStyle = Element.Methods.getStyle;
 Element.Methods.getStyle = function(element, style) {
  switch(style) {
   case 'left':
   case 'top':
   case 'right':
   case 'bottom':
    if (Element._getStyle(element, 'position') == 'static') return null;
   default: return Element._getStyle(element, style);
  }
 };
}
else if (Prototype.Browser.IE) {
 Element.Methods.getStyle = function(element, style) {
  element = $(element);
  style = (style == 'float' || style == 'cssFloat') ? 'styleFloat' : style.camelize();
  var value = element.style[style];
  if (!value && element.currentStyle) value = element.currentStyle[style];

  if (style == 'opacity') {
   if (value = (element.getStyle('filter') || '').match(/alpha\(opacity=(.*)\)/))
    if (value[1]) return parseFloat(value[1]) / 100;
   return 1.0;
  }

  if (value == 'auto') {
   if ((style == 'width' || style == 'height') && (element.getStyle('display') != 'none'))
    return element['offset'+style.capitalize()] + 'px';
   return null;
  }
  return value;
 };

 Element.Methods.setOpacity = function(element, value) {
  element = $(element);
  var filter = element.getStyle('filter'), style = element.style;
  if (value == 1 || value === '') {
   style.filter = filter.replace(/alpha\([^\)]*\)/gi,'');
   return element;
  } else if (value < 0.00001) value = 0;
  style.filter = filter.replace(/alpha\([^\)]*\)/gi, '') +
   'alpha(opacity=' + (value * 100) + ')';
  return element;
 };


 Element.Methods.update = function(element, html) {
  element = $(element);
  html = typeof html == 'undefined' ? '' : html.toString();
  var tagName = element.tagName.toUpperCase();
  if (['THEAD','TBODY','TR','TD'].include(tagName)) {
   var div = document.createElement('div');
   switch (tagName) {
    case 'THEAD':
    case 'TBODY':
     div.innerHTML = '<table><tbody>' + html.stripScripts() + '</tbody></table>';
     depth = 2;
     break;
    case 'TR':
     div.innerHTML = '<table><tbody><tr>' + html.stripScripts() + '</tr></tbody></table>';
     depth = 3;
     break;
    case 'TD':
     div.innerHTML = '<table><tbody><tr><td>' + html.stripScripts() + '</td></tr></tbody></table>';
     depth = 4;
   }
   $A(element.childNodes).each(function(node) { element.removeChild(node) });
   depth.times(function() { div = div.firstChild });
   $A(div.childNodes).each(function(node) { element.appendChild(node) });
  } else {
   element.innerHTML = html.stripScripts();
  }
  setTimeout(function() { html.evalScripts() }, 10);
  return element;
 }
}
else if (Prototype.Browser.Gecko) {
 Element.Methods.setOpacity = function(element, value) {
  element = $(element);
  element.style.opacity = (value == 1) ? 0.999999 :
   (value === '') ? '' : (value < 0.00001) ? 0 : value;
  return element;
 };
}

Element._attributeTranslations = {
 names: {
  colspan:  "colSpan",
  rowspan:  "rowSpan",
  valign:  "vAlign",
  datetime: "dateTime",
  accesskey: "accessKey",
  tabindex: "tabIndex",
  enctype:  "encType",
  maxlength: "maxLength",
  readonly: "readOnly",
  longdesc: "longDesc"
 },
 values: {
  _getAttr: function(element, attribute) {
   return element.getAttribute(attribute, 2);
  },
  _flag: function(element, attribute) {
   return $(element).hasAttribute(attribute) ? attribute : null;
  },
  style: function(element) {
   return element.style.cssText.toLowerCase();
  },
  title: function(element) {
   var node = element.getAttributeNode('title');
   return node.specified ? node.nodeValue : null;
  }
 }
};

(function() {
 Object.extend(this, {
  href: this._getAttr,
  src: this._getAttr,
  type: this._getAttr,
  disabled: this._flag,
  checked: this._flag,
  readonly: this._flag,
  multiple: this._flag
 });
}).call(Element._attributeTranslations.values);

Element.Methods.Simulated = {
 hasAttribute: function(element, attribute) {
  var t = Element._attributeTranslations, node;
  attribute = t.names[attribute] || attribute;
  node = $(element).getAttributeNode(attribute);
  return node && node.specified;
 }
};

Element.Methods.ByTag = {};

Object.extend(Element, Element.Methods);

if (!Prototype.BrowserFeatures.ElementExtensions &&
 document.createElement('div').__proto__) {
 window.HTMLElement = {};
 window.HTMLElement.prototype = document.createElement('div').__proto__;
 Prototype.BrowserFeatures.ElementExtensions = true;
}

Element.hasAttribute = function(element, attribute) {
 if (element.hasAttribute) return element.hasAttribute(attribute);
 return Element.Methods.Simulated.hasAttribute(element, attribute);
};

Element.addMethods = function(methods) {
 var F = Prototype.BrowserFeatures, T = Element.Methods.ByTag;

 if (!methods) {
  Object.extend(Form, Form.Methods);
  Object.extend(Form.Element, Form.Element.Methods);
  Object.extend(Element.Methods.ByTag, {
   "FORM":   Object.clone(Form.Methods),
   "INPUT":  Object.clone(Form.Element.Methods),
   "SELECT":  Object.clone(Form.Element.Methods),
   "TEXTAREA": Object.clone(Form.Element.Methods)
  });
 }

 if (arguments.length == 2) {
  var tagName = methods;
  methods = arguments[1];
 }

 if (!tagName) Object.extend(Element.Methods, methods || {});
 else {
  if (tagName.constructor == Array) tagName.each(extend);
  else extend(tagName);
 }

 function extend(tagName) {
  tagName = tagName.toUpperCase();
  if (!Element.Methods.ByTag[tagName])
   Element.Methods.ByTag[tagName] = {};
  Object.extend(Element.Methods.ByTag[tagName], methods);
 }

 function copy(methods, destination, onlyIfAbsent) {
  onlyIfAbsent = onlyIfAbsent || false;
  var cache = Element.extend.cache;
  for (var property in methods) {
   var value = methods[property];
   if (!onlyIfAbsent || !(property in destination))
    destination[property] = cache.findOrStore(value);
  }
 }

 function findDOMClass(tagName) {
  var klass;
  var trans = {
   "OPTGROUP": "OptGroup", "TEXTAREA": "TextArea", "P": "Paragraph",
   "FIELDSET": "FieldSet", "UL": "UList", "OL": "OList", "DL": "DList",
   "DIR": "Directory", "H1": "Heading", "H2": "Heading", "H3": "Heading",
   "H4": "Heading", "H5": "Heading", "H6": "Heading", "Q": "Quote",
   "INS": "Mod", "DEL": "Mod", "A": "Anchor", "IMG": "Image", "CAPTION":
   "TableCaption", "COL": "TableCol", "COLGROUP": "TableCol", "THEAD":
   "TableSection", "TFOOT": "TableSection", "TBODY": "TableSection", "TR":
   "TableRow", "TH": "TableCell", "TD": "TableCell", "FRAMESET":
   "FrameSet", "IFRAME": "IFrame"
  };
  if (trans[tagName]) klass = 'HTML' + trans[tagName] + 'Element';
  if (window[klass]) return window[klass];
  klass = 'HTML' + tagName + 'Element';
  if (window[klass]) return window[klass];
  klass = 'HTML' + tagName.capitalize() + 'Element';
  if (window[klass]) return window[klass];

  window[klass] = {};
  window[klass].prototype = document.createElement(tagName).__proto__;
  return window[klass];
 }

 if (F.ElementExtensions) {
  copy(Element.Methods, HTMLElement.prototype);
  copy(Element.Methods.Simulated, HTMLElement.prototype, true);
 }

 if (F.SpecificElementExtensions) {
  for (var tag in Element.Methods.ByTag) {
   var klass = findDOMClass(tag);
   if (typeof klass == "undefined") continue;
   copy(T[tag], klass.prototype);
  }
 }

 Object.extend(Element, Element.Methods);
 delete Element.ByTag;
};

var Toggle = { display: Element.toggle };

/*--------------------------------------------------------------------------*/

Abstract.Insertion = function(adjacency) {
 this.adjacency = adjacency;
}

Abstract.Insertion.prototype = {
 initialize: function(element, content) {
  this.element = $(element);
  this.content = content.stripScripts();

  if (this.adjacency && this.element.insertAdjacentHTML) {
   try {
    this.element.insertAdjacentHTML(this.adjacency, this.content);
   } catch (e) {
    var tagName = this.element.tagName.toUpperCase();
    if (['TBODY', 'TR'].include(tagName)) {
     this.insertContent(this.contentFromAnonymousTable());
    } else {
     throw e;
    }
   }
  } else {
   this.range = this.element.ownerDocument.createRange();
   if (this.initializeRange) this.initializeRange();
   this.insertContent([this.range.createContextualFragment(this.content)]);
  }

  setTimeout(function() {content.evalScripts()}, 10);
 },

 contentFromAnonymousTable: function() {
  var div = document.createElement('div');
  div.innerHTML = '<table><tbody>' + this.content + '</tbody></table>';
  return $A(div.childNodes[0].childNodes[0].childNodes);
 }
}

var Insertion = new Object();

Insertion.Before = Class.create();
Insertion.Before.prototype = Object.extend(new Abstract.Insertion('beforeBegin'), {
 initializeRange: function() {
  this.range.setStartBefore(this.element);
 },

 insertContent: function(fragments) {
  fragments.each((function(fragment) {
   this.element.parentNode.insertBefore(fragment, this.element);
  }).bind(this));
 }
});

Insertion.Top = Class.create();
Insertion.Top.prototype = Object.extend(new Abstract.Insertion('afterBegin'), {
 initializeRange: function() {
  this.range.selectNodeContents(this.element);
  this.range.collapse(true);
 },

 insertContent: function(fragments) {
  fragments.reverse(false).each((function(fragment) {
   this.element.insertBefore(fragment, this.element.firstChild);
  }).bind(this));
 }
});

Insertion.Bottom = Class.create();
Insertion.Bottom.prototype = Object.extend(new Abstract.Insertion('beforeEnd'), {
 initializeRange: function() {
  this.range.selectNodeContents(this.element);
  this.range.collapse(this.element);
 },

 insertContent: function(fragments) {
  fragments.each((function(fragment) {
   this.element.appendChild(fragment);
  }).bind(this));
 }
});

Insertion.After = Class.create();
Insertion.After.prototype = Object.extend(new Abstract.Insertion('afterEnd'), {
 initializeRange: function() {
  this.range.setStartAfter(this.element);
 },

 insertContent: function(fragments) {
  fragments.each((function(fragment) {
   this.element.parentNode.insertBefore(fragment,
    this.element.nextSibling);
  }).bind(this));
 }
});

/*--------------------------------------------------------------------------*/

Element.ClassNames = Class.create();
Element.ClassNames.prototype = {
 initialize: function(element) {
  this.element = $(element);
 },

 _each: function(iterator) {
  this.element.className.split(/\s+/).select(function(name) {
   return name.length > 0;
  })._each(iterator);
 },

 set: function(className) {
  this.element.className = className;
 },

 add: function(classNameToAdd) {
  if (this.include(classNameToAdd)) return;
  this.set($A(this).concat(classNameToAdd).join(' '));
 },

 remove: function(classNameToRemove) {
  if (!this.include(classNameToRemove)) return;
  this.set($A(this).without(classNameToRemove).join(' '));
 },

 toString: function() {
  return $A(this).join(' ');
 }
};

Object.extend(Element.ClassNames.prototype, Enumerable);


var Selector = Class.create();

Selector.prototype = {
 initialize: function(expression) {
  this.expression = expression.strip();
  this.compileMatcher();
 },

 compileMatcher: function() {

  if (Prototype.BrowserFeatures.XPath && !(/\[[\w-]*?:/).test(this.expression))
   return this.compileXPathMatcher();

  var e = this.expression, ps = Selector.patterns, h = Selector.handlers,
    c = Selector.criteria, le, p, m;

  if (Selector._cache[e]) {
   this.matcher = Selector._cache[e]; return;
  }
  this.matcher = ["this.matcher = function(root) {",
          "var r = root, h = Selector.handlers, c = false, n;"];

  while (e && le != e && (/\S/).test(e)) {
   le = e;
   for (var i in ps) {
    p = ps[i];
    if (m = e.match(p)) {
     this.matcher.push(typeof c[i] == 'function' ? c[i](m) :
  	   new Template(c[i]).evaluate(m));
     e = e.replace(m[0], '');
     break;
    }
   }
  }

  this.matcher.push("return h.unique(n);\n}");
  eval(this.matcher.join('\n'));
  Selector._cache[this.expression] = this.matcher;
 },

 compileXPathMatcher: function() {
  var e = this.expression, ps = Selector.patterns,
    x = Selector.xpath, le, m;

  if (Selector._cache[e]) {
   this.xpath = Selector._cache[e]; return;
  }

  this.matcher = ['.//*'];
  while (e && le != e && (/\S/).test(e)) {
   le = e;
   for (var i in ps) {
    if (m = e.match(ps[i])) {
     this.matcher.push(typeof x[i] == 'function' ? x[i](m) :
      new Template(x[i]).evaluate(m));
     e = e.replace(m[0], '');
     break;
    }
   }
  }

  this.xpath = this.matcher.join('');
  Selector._cache[this.expression] = this.xpath;
 },

 findElements: function(root) {
  root = root || document;
  if (this.xpath) return document._getElementsByXPath(this.xpath, root);
  return this.matcher(root);
 },

 match: function(element) {
  return this.findElements(document).include(element);
 },

 toString: function() {
  return this.expression;
 },

 inspect: function() {
  return "#<Selector:" + this.expression.inspect() + ">";
 }
};

Object.extend(Selector, {
 _cache: {},

 xpath: {
  descendant:  "//*",
  child:    "/*",
  adjacent:   "/following-sibling::*[1]",
  laterSibling: '/following-sibling::*',
  tagName:   function(m) {
   if (m[1] == '*') return '';
   return "[local-name()='" + m[1].toLowerCase() +
       "' or local-name()='" + m[1].toUpperCase() + "']";
  },
  className:  "[contains(concat(' ', @class, ' '), ' #{1} ')]",
  id:      "[@id='#{1}']",
  attrPresence: "[@#{1}]",
  attr: function(m) {
   m[3] = m[5] || m[6];
   return new Template(Selector.xpath.operators[m[2]]).evaluate(m);
  },
  pseudo: function(m) {
   var h = Selector.xpath.pseudos[m[1]];
   if (!h) return '';
   if (typeof h === 'function') return h(m);
   return new Template(Selector.xpath.pseudos[m[1]]).evaluate(m);
  },
  operators: {
   '=': "[@#{1}='#{3}']",
   '!=': "[@#{1}!='#{3}']",
   '^=': "[starts-with(@#{1}, '#{3}')]",
   '$=': "[substring(@#{1}, (string-length(@#{1}) - string-length('#{3}') + 1))='#{3}']",
   '*=': "[contains(@#{1}, '#{3}')]",
   '~=': "[contains(concat(' ', @#{1}, ' '), ' #{3} ')]",
   '|=': "[contains(concat('-', @#{1}, '-'), '-#{3}-')]"
  },
  pseudos: {
   'first-child': '[not(preceding-sibling::*)]',
   'last-child': '[not(following-sibling::*)]',
   'only-child': '[not(preceding-sibling::* or following-sibling::*)]',
   'empty':    "[count(*) = 0 and (count(text()) = 0 or translate(text(), ' \t\r\n', '') = '')]",
   'checked':   "[@checked]",
   'disabled':  "[@disabled]",
   'enabled':   "[not(@disabled)]",
   'not': function(m) {
    var e = m[6], p = Selector.patterns,
      x = Selector.xpath, le, m, v;

    var exclusion = [];
    while (e && le != e && (/\S/).test(e)) {
     le = e;
     for (var i in p) {
      if (m = e.match(p[i])) {
       v = typeof x[i] == 'function' ? x[i](m) : new Template(x[i]).evaluate(m);
       exclusion.push("(" + v.substring(1, v.length - 1) + ")");
       e = e.replace(m[0], '');
       break;
      }
     }
    }
    return "[not(" + exclusion.join(" and ") + ")]";
   },
   'nth-child':   function(m) {
    return Selector.xpath.pseudos.nth("(count(./preceding-sibling::*) + 1) ", m);
   },
   'nth-last-child': function(m) {
    return Selector.xpath.pseudos.nth("(count(./following-sibling::*) + 1) ", m);
   },
   'nth-of-type':  function(m) {
    return Selector.xpath.pseudos.nth("position() ", m);
   },
   'nth-last-of-type': function(m) {
    return Selector.xpath.pseudos.nth("(last() + 1 - position()) ", m);
   },
   'first-of-type': function(m) {
    m[6] = "1"; return Selector.xpath.pseudos['nth-of-type'](m);
   },
   'last-of-type':  function(m) {
    m[6] = "1"; return Selector.xpath.pseudos['nth-last-of-type'](m);
   },
   'only-of-type':  function(m) {
    var p = Selector.xpath.pseudos; return p['first-of-type'](m) + p['last-of-type'](m);
   },
   nth: function(fragment, m) {
    var mm, formula = m[6], predicate;
    if (formula == 'even') formula = '2n+0';
    if (formula == 'odd') formula = '2n+1';
    if (mm = formula.match(/^(\d+)$/)) 
     return '[' + fragment + "= " + mm[1] + ']';
    if (mm = formula.match(/^(-?\d*)?n(([+-])(\d+))?/)) { 
     if (mm[1] == "-") mm[1] = -1;
     var a = mm[1] ? Number(mm[1]) : 1;
     var b = mm[2] ? Number(mm[2]) : 0;
     predicate = "[((#{fragment} - #{b}) mod #{a} = 0) and " +
     "((#{fragment} - #{b}) div #{a} >= 0)]";
     return new Template(predicate).evaluate({
      fragment: fragment, a: a, b: b });
    }
   }
  }
 },

 criteria: {
  tagName:   'n = h.tagName(n, r, "#{1}", c);  c = false;',
  className:  'n = h.className(n, r, "#{1}", c); c = false;',
  id:      'n = h.id(n, r, "#{1}", c);    c = false;',
  attrPresence: 'n = h.attrPresence(n, r, "#{1}"); c = false;',
  attr: function(m) {
   m[3] = (m[5] || m[6]);
   return new Template('n = h.attr(n, r, "#{1}", "#{3}", "#{2}"); c = false;').evaluate(m);
  },
  pseudo:    function(m) {
   if (m[6]) m[6] = m[6].replace(/"/g, '\\"');
   return new Template('n = h.pseudo(n, "#{1}", "#{6}", r, c); c = false;').evaluate(m);
  },
  descendant:  'c = "descendant";',
  child:    'c = "child";',
  adjacent:   'c = "adjacent";',
  laterSibling: 'c = "laterSibling";'
 },

 patterns: {

  laterSibling: /^\s*~\s*/,
  child:    /^\s*>\s*/,
  adjacent:   /^\s*\+\s*/,
  descendant:  /^\s/,


  tagName:   /^\s*(\*|[\w\-]+)(\b|$)?/,
  id:      /^#([\w\-\*]+)(\b|$)/,
  className:  /^\.([\w\-\*]+)(\b|$)/,
  pseudo:    /^:((first|last|nth|nth-last|only)(-child|-of-type)|empty|checked|(en|dis)abled|not)(\((.*?)\))?(\b|$|\s|(?=:))/,
  attrPresence: /^\[([\w]+)\]/,
  attr:     /\[((?:[\w-]*:)?[\w-]+)\s*(?:([!^$*~|]?=)\s*((['"])([^\]]*?)\4|([^'"][^\]]*?)))?\]/
 },

 handlers: {

  concat: function(a, b) {
   for (var i = 0, node; node = b[i]; i++)
    a.push(node);
   return a;
  },


  mark: function(nodes) {
   for (var i = 0, node; node = nodes[i]; i++)
    node._counted = true;
   return nodes;
  },

  unmark: function(nodes) {
   for (var i = 0, node; node = nodes[i]; i++)
    node._counted = undefined;
   return nodes;
  },


  index: function(parentNode, reverse, ofType) {
   parentNode._counted = true;
   if (reverse) {
    for (var nodes = parentNode.childNodes, i = nodes.length - 1, j = 1; i >= 0; i--) {
     node = nodes[i];
     if (node.nodeType == 1 && (!ofType || node._counted)) node.nodeIndex = j++;
    }
   } else {
    for (var i = 0, j = 1, nodes = parentNode.childNodes; node = nodes[i]; i++)
     if (node.nodeType == 1 && (!ofType || node._counted)) node.nodeIndex = j++;
   }
  },


  unique: function(nodes) {
   if (nodes.length == 0) return nodes;
   var results = [], n;
   for (var i = 0, l = nodes.length; i < l; i++)
    if (!(n = nodes[i])._counted) {
     n._counted = true;
     results.push(Element.extend(n));
    }
   return Selector.handlers.unmark(results);
  },


  descendant: function(nodes) {
   var h = Selector.handlers;
   for (var i = 0, results = [], node; node = nodes[i]; i++)
    h.concat(results, node.getElementsByTagName('*'));
   return results;
  },

  child: function(nodes) {
   var h = Selector.handlers;
   for (var i = 0, results = [], node; node = nodes[i]; i++) {
    for (var j = 0, children = [], child; child = node.childNodes[j]; j++)
     if (child.nodeType == 1 && child.tagName != '!') results.push(child);
   }
   return results;
  },

  adjacent: function(nodes) {
   for (var i = 0, results = [], node; node = nodes[i]; i++) {
    var next = this.nextElementSibling(node);
    if (next) results.push(next);
   }
   return results;
  },

  laterSibling: function(nodes) {
   var h = Selector.handlers;
   for (var i = 0, results = [], node; node = nodes[i]; i++)
    h.concat(results, Element.nextSiblings(node));
   return results;
  },

  nextElementSibling: function(node) {
   while (node = node.nextSibling)
	   if (node.nodeType == 1) return node;
   return null;
  },

  previousElementSibling: function(node) {
   while (node = node.previousSibling)
    if (node.nodeType == 1) return node;
   return null;
  },


  tagName: function(nodes, root, tagName, combinator) {
   tagName = tagName.toUpperCase();
   var results = [], h = Selector.handlers;
   if (nodes) {
    if (combinator) {

     if (combinator == "descendant") {
      for (var i = 0, node; node = nodes[i]; i++)
       h.concat(results, node.getElementsByTagName(tagName));
      return results;
     } else nodes = this[combinator](nodes);
     if (tagName == "*") return nodes;
    }
    for (var i = 0, node; node = nodes[i]; i++)
     if (node.tagName.toUpperCase() == tagName) results.push(node);
    return results;
   } else return root.getElementsByTagName(tagName);
  },

  id: function(nodes, root, id, combinator) {
   var targetNode = $(id), h = Selector.handlers;
   if (!nodes && root == document) return targetNode ? [targetNode] : [];
   if (nodes) {
    if (combinator) {
     if (combinator == 'child') {
      for (var i = 0, node; node = nodes[i]; i++)
       if (targetNode.parentNode == node) return [targetNode];
     } else if (combinator == 'descendant') {
      for (var i = 0, node; node = nodes[i]; i++)
       if (Element.descendantOf(targetNode, node)) return [targetNode];
     } else if (combinator == 'adjacent') {
      for (var i = 0, node; node = nodes[i]; i++)
       if (Selector.handlers.previousElementSibling(targetNode) == node)
        return [targetNode];
     } else nodes = h[combinator](nodes);
    }
    for (var i = 0, node; node = nodes[i]; i++)
     if (node == targetNode) return [targetNode];
    return [];
   }
   return (targetNode && Element.descendantOf(targetNode, root)) ? [targetNode] : [];
  },

  className: function(nodes, root, className, combinator) {
   if (nodes && combinator) nodes = this[combinator](nodes);
   return Selector.handlers.byClassName(nodes, root, className);
  },

  byClassName: function(nodes, root, className) {
   if (!nodes) nodes = Selector.handlers.descendant([root]);
   var needle = ' ' + className + ' ';
   for (var i = 0, results = [], node, nodeClassName; node = nodes[i]; i++) {
    nodeClassName = node.className;
    if (nodeClassName.length == 0) continue;
    if (nodeClassName == className || (' ' + nodeClassName + ' ').include(needle))
     results.push(node);
   }
   return results;
  },

  attrPresence: function(nodes, root, attr) {
   var results = [];
   for (var i = 0, node; node = nodes[i]; i++)
    if (Element.hasAttribute(node, attr)) results.push(node);
   return results;
  },

  attr: function(nodes, root, attr, value, operator) {
   if (!nodes) nodes = root.getElementsByTagName("*");
   var handler = Selector.operators[operator], results = [];
   for (var i = 0, node; node = nodes[i]; i++) {
    var nodeValue = Element.readAttribute(node, attr);
    if (nodeValue === null) continue;
    if (handler(nodeValue, value)) results.push(node);
   }
   return results;
  },

  pseudo: function(nodes, name, value, root, combinator) {
   if (nodes && combinator) nodes = this[combinator](nodes);
   if (!nodes) nodes = root.getElementsByTagName("*");
   return Selector.pseudos[name](nodes, value, root);
  }
 },

 pseudos: {
  'first-child': function(nodes, value, root) {
   for (var i = 0, results = [], node; node = nodes[i]; i++) {
    if (Selector.handlers.previousElementSibling(node)) continue;
     results.push(node);
   }
   return results;
  },
  'last-child': function(nodes, value, root) {
   for (var i = 0, results = [], node; node = nodes[i]; i++) {
    if (Selector.handlers.nextElementSibling(node)) continue;
     results.push(node);
   }
   return results;
  },
  'only-child': function(nodes, value, root) {
   var h = Selector.handlers;
   for (var i = 0, results = [], node; node = nodes[i]; i++)
    if (!h.previousElementSibling(node) && !h.nextElementSibling(node))
     results.push(node);
   return results;
  },
  'nth-child':    function(nodes, formula, root) {
   return Selector.pseudos.nth(nodes, formula, root);
  },
  'nth-last-child':  function(nodes, formula, root) {
   return Selector.pseudos.nth(nodes, formula, root, true);
  },
  'nth-of-type':   function(nodes, formula, root) {
   return Selector.pseudos.nth(nodes, formula, root, false, true);
  },
  'nth-last-of-type': function(nodes, formula, root) {
   return Selector.pseudos.nth(nodes, formula, root, true, true);
  },
  'first-of-type':  function(nodes, formula, root) {
   return Selector.pseudos.nth(nodes, "1", root, false, true);
  },
  'last-of-type':   function(nodes, formula, root) {
   return Selector.pseudos.nth(nodes, "1", root, true, true);
  },
  'only-of-type':   function(nodes, formula, root) {
   var p = Selector.pseudos;
   return p['last-of-type'](p['first-of-type'](nodes, formula, root), formula, root);
  },


  getIndices: function(a, b, total) {
   if (a == 0) return b > 0 ? [b] : [];
   return $R(1, total).inject([], function(memo, i) {
    if (0 == (i - b) % a && (i - b) / a >= 0) memo.push(i);
    return memo;
   });
  },


  nth: function(nodes, formula, root, reverse, ofType) {
   if (nodes.length == 0) return [];
   if (formula == 'even') formula = '2n+0';
   if (formula == 'odd') formula = '2n+1';
   var h = Selector.handlers, results = [], indexed = [], m;
   h.mark(nodes);
   for (var i = 0, node; node = nodes[i]; i++) {
    if (!node.parentNode._counted) {
     h.index(node.parentNode, reverse, ofType);
     indexed.push(node.parentNode);
    }
   }
   if (formula.match(/^\d+$/)) { 
    formula = Number(formula);
    for (var i = 0, node; node = nodes[i]; i++)
     if (node.nodeIndex == formula) results.push(node);
   } else if (m = formula.match(/^(-?\d*)?n(([+-])(\d+))?/)) { 
    if (m[1] == "-") m[1] = -1;
    var a = m[1] ? Number(m[1]) : 1;
    var b = m[2] ? Number(m[2]) : 0;
    var indices = Selector.pseudos.getIndices(a, b, nodes.length);
    for (var i = 0, node, l = indices.length; node = nodes[i]; i++) {
     for (var j = 0; j < l; j++)
      if (node.nodeIndex == indices[j]) results.push(node);
    }
   }
   h.unmark(nodes);
   h.unmark(indexed);
   return results;
  },

  'empty': function(nodes, value, root) {
   for (var i = 0, results = [], node; node = nodes[i]; i++) {
   
    if (node.tagName == '!' || (node.firstChild && !node.innerHTML.match(/^\s*$/))) continue;
    results.push(node);
   }
   return results;
  },

  'not': function(nodes, selector, root) {
   var h = Selector.handlers, selectorType, m;
   var exclusions = new Selector(selector).findElements(root);
   h.mark(exclusions);
   for (var i = 0, results = [], node; node = nodes[i]; i++)
    if (!node._counted) results.push(node);
   h.unmark(exclusions);
   return results;
  },

  'enabled': function(nodes, value, root) {
   for (var i = 0, results = [], node; node = nodes[i]; i++)
    if (!node.disabled) results.push(node);
   return results;
  },

  'disabled': function(nodes, value, root) {
   for (var i = 0, results = [], node; node = nodes[i]; i++)
    if (node.disabled) results.push(node);
   return results;
  },

  'checked': function(nodes, value, root) {
   for (var i = 0, results = [], node; node = nodes[i]; i++)
    if (node.checked) results.push(node);
   return results;
  }
 },

 operators: {
  '=': function(nv, v) { return nv == v; },
  '!=': function(nv, v) { return nv != v; },
  '^=': function(nv, v) { return nv.startsWith(v); },
  '$=': function(nv, v) { return nv.endsWith(v); },
  '*=': function(nv, v) { return nv.include(v); },
  '~=': function(nv, v) { return (' ' + nv + ' ').include(' ' + v + ' '); },
  '|=': function(nv, v) { return ('-' + nv.toUpperCase() + '-').include('-' + v.toUpperCase() + '-'); }
 },

 matchElements: function(elements, expression) {
  var matches = new Selector(expression).findElements(), h = Selector.handlers;
  h.mark(matches);
  for (var i = 0, results = [], element; element = elements[i]; i++)
   if (element._counted) results.push(element);
  h.unmark(matches);
  return results;
 },

 findElement: function(elements, expression, index) {
  if (typeof expression == 'number') {
   index = expression; expression = false;
  }
  return Selector.matchElements(elements, expression || '*')[index || 0];
 },

 findChildElements: function(element, expressions) {
  var exprs = expressions.join(','), expressions = [];
  exprs.scan(/(([\w#:.~>+()\s-]+|\*|\[.*?\])+)\s*(,|$)/, function(m) {
   expressions.push(m[1].strip());
  });
  var results = [], h = Selector.handlers;
  for (var i = 0, l = expressions.length, selector; i < l; i++) {
   selector = new Selector(expressions[i].strip());
   h.concat(results, selector.findElements(element));
  }
  return (l > 1) ? h.unique(results) : results;
 }
});

function $$() {
 return Selector.findChildElements(document, $A(arguments));
}
var Form = {
 reset: function(form) {
  $(form).reset();
  return form;
 },

 serializeElements: function(elements, getHash) {
  var data = elements.inject({}, function(result, element) {
   if (!element.disabled && element.name) {
    var key = element.name, value = $(element).getValue();
    if (value != null) {
     	if (key in result) {
      if (result[key].constructor != Array) result[key] = [result[key]];
      result[key].push(value);
     }
     else result[key] = value;
    }
   }
   return result;
  });

  return getHash ? data : Hash.toQueryString(data);
 }
};

Form.Methods = {
 serialize: function(form, getHash) {
  return Form.serializeElements(Form.getElements(form), getHash);
 },

 getElements: function(form) {
  return $A($(form).getElementsByTagName('*')).inject([],
   function(elements, child) {
    if (Form.Element.Serializers[child.tagName.toLowerCase()])
     elements.push(Element.extend(child));
    return elements;
   }
  );
 },

 getInputs: function(form, typeName, name) {
  form = $(form);
  var inputs = form.getElementsByTagName('input');

  if (!typeName && !name) return $A(inputs).map(Element.extend);

  for (var i = 0, matchingInputs = [], length = inputs.length; i < length; i++) {
   var input = inputs[i];
   if ((typeName && input.type != typeName) || (name && input.name != name))
    continue;
   matchingInputs.push(Element.extend(input));
  }

  return matchingInputs;
 },

 disable: function(form) {
  form = $(form);
  Form.getElements(form).invoke('disable');
  return form;
 },

 enable: function(form) {
  form = $(form);
  Form.getElements(form).invoke('enable');
  return form;
 },

 findFirstElement: function(form) {
  return $(form).getElements().find(function(element) {
   return element.type != 'hidden' && !element.disabled &&
    ['input', 'select', 'textarea'].include(element.tagName.toLowerCase());
  });
 },

 focusFirstElement: function(form) {
  form = $(form);
  form.findFirstElement().activate();
  return form;
 },

 request: function(form, options) {
  form = $(form), options = Object.clone(options || {});

  var params = options.parameters;
  options.parameters = form.serialize(true);

  if (params) {
   if (typeof params == 'string') params = params.toQueryParams();
   Object.extend(options.parameters, params);
  }

  if (form.hasAttribute('method') && !options.method)
   options.method = form.method;

  return new Ajax.Request(form.readAttribute('action'), options);
 }
}

/*--------------------------------------------------------------------------*/

Form.Element = {
 focus: function(element) {
  $(element).focus();
  return element;
 },

 select: function(element) {
  $(element).select();
  return element;
 }
}

Form.Element.Methods = {
 serialize: function(element) {
  element = $(element);
  if (!element.disabled && element.name) {
   var value = element.getValue();
   if (value != undefined) {
    var pair = {};
    pair[element.name] = value;
    return Hash.toQueryString(pair);
   }
  }
  return '';
 },

 getValue: function(element) {
  element = $(element);
  var method = element.tagName.toLowerCase();
  return Form.Element.Serializers[method](element);
 },

 clear: function(element) {
  $(element).value = '';
  return element;
 },

 present: function(element) {
  return $(element).value != '';
 },

 activate: function(element) {
  element = $(element);
  try {
   element.focus();
   if (element.select && (element.tagName.toLowerCase() != 'input' ||
    !['button', 'reset', 'submit'].include(element.type)))
    element.select();
  } catch (e) {}
  return element;
 },

 disable: function(element) {
  element = $(element);
  element.blur();
  element.disabled = true;
  return element;
 },

 enable: function(element) {
  element = $(element);
  element.disabled = false;
  return element;
 }
}

/*--------------------------------------------------------------------------*/

var Field = Form.Element;
var $F = Form.Element.Methods.getValue;

/*--------------------------------------------------------------------------*/

Form.Element.Serializers = {
 input: function(element) {
  switch (element.type.toLowerCase()) {
   case 'checkbox':
   case 'radio':
    return Form.Element.Serializers.inputSelector(element);
   default:
    return Form.Element.Serializers.textarea(element);
  }
 },

 inputSelector: function(element) {
  return element.checked ? element.value : null;
 },

 textarea: function(element) {
  return element.value;
 },

 select: function(element) {
  return this[element.type == 'select-one' ?
   'selectOne' : 'selectMany'](element);
 },

 selectOne: function(element) {
  var index = element.selectedIndex;
  return index >= 0 ? this.optionValue(element.options[index]) : null;
 },

 selectMany: function(element) {
  var values, length = element.length;
  if (!length) return null;

  for (var i = 0, values = []; i < length; i++) {
   var opt = element.options[i];
   if (opt.selected) values.push(this.optionValue(opt));
  }
  return values;
 },

 optionValue: function(opt) {
  
  return Element.extend(opt).hasAttribute('value') ? opt.value : opt.text;
 }
}

/*--------------------------------------------------------------------------*/

Abstract.TimedObserver = function() {}
Abstract.TimedObserver.prototype = {
 initialize: function(element, frequency, callback) {
  this.frequency = frequency;
  this.element  = $(element);
  this.callback = callback;

  this.lastValue = this.getValue();
  this.registerCallback();
 },

 registerCallback: function() {
  setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
 },

 onTimerEvent: function() {
  var value = this.getValue();
  var changed = ('string' == typeof this.lastValue && 'string' == typeof value
   ? this.lastValue != value : String(this.lastValue) != String(value));
  if (changed) {
   this.callback(this.element, value);
   this.lastValue = value;
  }
 }
}

Form.Element.Observer = Class.create();
Form.Element.Observer.prototype = Object.extend(new Abstract.TimedObserver(), {
 getValue: function() {
  return Form.Element.getValue(this.element);
 }
});

Form.Observer = Class.create();
Form.Observer.prototype = Object.extend(new Abstract.TimedObserver(), {
 getValue: function() {
  return Form.serialize(this.element);
 }
});

/*--------------------------------------------------------------------------*/

Abstract.EventObserver = function() {}
Abstract.EventObserver.prototype = {
 initialize: function(element, callback) {
  this.element = $(element);
  this.callback = callback;

  this.lastValue = this.getValue();
  if (this.element.tagName.toLowerCase() == 'form')
   this.registerFormCallbacks();
  else
   this.registerCallback(this.element);
 },

 onElementEvent: function() {
  var value = this.getValue();
  if (this.lastValue != value) {
   this.callback(this.element, value);
   this.lastValue = value;
  }
 },

 registerFormCallbacks: function() {
  Form.getElements(this.element).each(this.registerCallback.bind(this));
 },

 registerCallback: function(element) {
  if (element.type) {
   switch (element.type.toLowerCase()) {
    case 'checkbox':
    case 'radio':
     Event.observe(element, 'click', this.onElementEvent.bind(this));
     break;
    default:
     Event.observe(element, 'change', this.onElementEvent.bind(this));
     break;
   }
  }
 }
}

Form.Element.EventObserver = Class.create();
Form.Element.EventObserver.prototype = Object.extend(new Abstract.EventObserver(), {
 getValue: function() {
  return Form.Element.getValue(this.element);
 }
});

Form.EventObserver = Class.create();
Form.EventObserver.prototype = Object.extend(new Abstract.EventObserver(), {
 getValue: function() {
  return Form.serialize(this.element);
 }
});
if (!window.Event) {
 var Event = new Object();
}

Object.extend(Event, {
 KEY_BACKSPACE: 8,
 KEY_TAB:    9,
 KEY_RETURN:  13,
 KEY_ESC:   27,
 KEY_LEFT:   37,
 KEY_UP:    38,
 KEY_RIGHT:  39,
 KEY_DOWN:   40,
 KEY_DELETE:  46,
 KEY_HOME:   36,
 KEY_END:   35,
 KEY_PAGEUP:  33,
 KEY_PAGEDOWN: 34,

 element: function(event) {
  return $(event.target || event.srcElement);
 },

 isLeftClick: function(event) {
  return (((event.which) && (event.which == 1)) ||
      ((event.button) && (event.button == 1)));
 },

 pointerX: function(event) {
  return event.pageX || (event.clientX +
   (document.documentElement.scrollLeft || document.body.scrollLeft));
 },

 pointerY: function(event) {
  return event.pageY || (event.clientY +
   (document.documentElement.scrollTop || document.body.scrollTop));
 },

 stop: function(event) {
  if (event.preventDefault) {
   event.preventDefault();
   event.stopPropagation();
  } else {
   event.returnValue = false;
   event.cancelBubble = true;
  }
 },


 findElement: function(event, tagName) {
  var element = Event.element(event);
  while (element.parentNode && (!element.tagName ||
    (element.tagName.toUpperCase() != tagName.toUpperCase())))
   element = element.parentNode;
  return element;
 },

 observers: false,

 _observeAndCache: function(element, name, observer, useCapture) {
  if (!this.observers) this.observers = [];
  if (element.addEventListener) {
   this.observers.push([element, name, observer, useCapture]);
   element.addEventListener(name, observer, useCapture);
  } else if (element.attachEvent) {
   this.observers.push([element, name, observer, useCapture]);
   element.attachEvent('on' + name, observer);
  }
 },

 unloadCache: function() {
  if (!Event.observers) return;
  for (var i = 0, length = Event.observers.length; i < length; i++) {
   Event.stopObserving.apply(this, Event.observers[i]);
   Event.observers[i][0] = null;
  }
  Event.observers = false;
 },

 observe: function(element, name, observer, useCapture) {
  element = $(element);
  useCapture = useCapture || false;

  if (name == 'keypress' &&
   (Prototype.Browser.WebKit || element.attachEvent))
   name = 'keydown';

  Event._observeAndCache(element, name, observer, useCapture);
 },

 stopObserving: function(element, name, observer, useCapture) {
  element = $(element);
  useCapture = useCapture || false;

  if (name == 'keypress' &&
    (Prototype.Browser.WebKit || element.attachEvent))
   name = 'keydown';

  if (element.removeEventListener) {
   element.removeEventListener(name, observer, useCapture);
  } else if (element.detachEvent) {
   try {
    element.detachEvent('on' + name, observer);
   } catch (e) {}
  }
 }
});

/* prevent memory leaks in IE */
if (Prototype.Browser.IE)
 Event.observe(window, 'unload', Event.unloadCache, false);
var Position = {

 includeScrollOffsets: false,


 prepare: function() {
  this.deltaX = window.pageXOffset
        || document.documentElement.scrollLeft
        || document.body.scrollLeft
        || 0;
  this.deltaY = window.pageYOffset
        || document.documentElement.scrollTop
        || document.body.scrollTop
        || 0;
 },

 realOffset: function(element) {
  var valueT = 0, valueL = 0;
  do {
   valueT += element.scrollTop || 0;
   valueL += element.scrollLeft || 0;
   element = element.parentNode;
  } while (element);
  return [valueL, valueT];
 },

 cumulativeOffset: function(element) {
  var valueT = 0, valueL = 0;
  do {
   valueT += element.offsetTop || 0;
   valueL += element.offsetLeft || 0;
   element = element.offsetParent;
  } while (element);
  return [valueL, valueT];
 },

 positionedOffset: function(element) {
  var valueT = 0, valueL = 0;
  do {
   valueT += element.offsetTop || 0;
   valueL += element.offsetLeft || 0;
   element = element.offsetParent;
   if (element) {
    if(element.tagName=='BODY') break;
    var p = Element.getStyle(element, 'position');
    if (p == 'relative' || p == 'absolute') break;
   }
  } while (element);
  return [valueL, valueT];
 },

 offsetParent: function(element) {
  if (element.offsetParent) return element.offsetParent;
  if (element == document.body) return element;

  while ((element = element.parentNode) && element != document.body)
   if (Element.getStyle(element, 'position') != 'static')
    return element;

  return document.body;
 },


 within: function(element, x, y) {
  if (this.includeScrollOffsets)
   return this.withinIncludingScrolloffsets(element, x, y);
  this.xcomp = x;
  this.ycomp = y;
  this.offset = this.cumulativeOffset(element);

  return (y >= this.offset[1] &&
      y < this.offset[1] + element.offsetHeight &&
      x >= this.offset[0] &&
      x < this.offset[0] + element.offsetWidth);
 },

 withinIncludingScrolloffsets: function(element, x, y) {
  var offsetcache = this.realOffset(element);

  this.xcomp = x + offsetcache[0] - this.deltaX;
  this.ycomp = y + offsetcache[1] - this.deltaY;
  this.offset = this.cumulativeOffset(element);

  return (this.ycomp >= this.offset[1] &&
      this.ycomp < this.offset[1] + element.offsetHeight &&
      this.xcomp >= this.offset[0] &&
      this.xcomp < this.offset[0] + element.offsetWidth);
 },


 overlap: function(mode, element) {
  if (!mode) return 0;
  if (mode == 'vertical')
   return ((this.offset[1] + element.offsetHeight) - this.ycomp) /
    element.offsetHeight;
  if (mode == 'horizontal')
   return ((this.offset[0] + element.offsetWidth) - this.xcomp) /
    element.offsetWidth;
 },

 page: function(forElement) {
  var valueT = 0, valueL = 0;

  var element = forElement;
  do {
   valueT += element.offsetTop || 0;
   valueL += element.offsetLeft || 0;


   if (element.offsetParent == document.body)
    if (Element.getStyle(element,'position')=='absolute') break;

  } while (element = element.offsetParent);

  element = forElement;
  do {
   if (!window.opera || element.tagName=='BODY') {
    valueT -= element.scrollTop || 0;
    valueL -= element.scrollLeft || 0;
   }
  } while (element = element.parentNode);

  return [valueL, valueT];
 },

 clone: function(source, target) {
  var options = Object.extend({
   setLeft:  true,
   setTop:   true,
   setWidth:  true,
   setHeight: true,
   offsetTop: 0,
   offsetLeft: 0
  }, arguments[2] || {})


  source = $(source);
  var p = Position.page(source);


  target = $(target);
  var delta = [0, 0];
  var parent = null;

  if (Element.getStyle(target,'position') == 'absolute') {
   parent = Position.offsetParent(target);
   delta = Position.page(parent);
  }


  if (parent == document.body) {
   delta[0] -= document.body.offsetLeft;
   delta[1] -= document.body.offsetTop;
  }


  if(options.setLeft)  target.style.left = (p[0] - delta[0] + options.offsetLeft) + 'px';
  if(options.setTop)  target.style.top  = (p[1] - delta[1] + options.offsetTop) + 'px';
  if(options.setWidth) target.style.width = source.offsetWidth + 'px';
  if(options.setHeight) target.style.height = source.offsetHeight + 'px';
 },

 absolutize: function(element) {
  element = $(element);
  if (element.style.position == 'absolute') return;
  Position.prepare();

  var offsets = Position.positionedOffset(element);
  var top   = offsets[1];
  var left  = offsets[0];
  var width  = element.clientWidth;
  var height = element.clientHeight;

  element._originalLeft  = left - parseFloat(element.style.left || 0);
  element._originalTop  = top - parseFloat(element.style.top || 0);
  element._originalWidth = element.style.width;
  element._originalHeight = element.style.height;

  element.style.position = 'absolute';
  element.style.top  = top + 'px';
  element.style.left  = left + 'px';
  element.style.width = width + 'px';
  element.style.height = height + 'px';
 },

 relativize: function(element) {
  element = $(element);
  if (element.style.position == 'relative') return;
  Position.prepare();

  element.style.position = 'relative';
  var top = parseFloat(element.style.top || 0) - (element._originalTop || 0);
  var left = parseFloat(element.style.left || 0) - (element._originalLeft || 0);

  element.style.top  = top + 'px';
  element.style.left  = left + 'px';
  element.style.height = element._originalHeight;
  element.style.width = element._originalWidth;
 }
}


if (Prototype.Browser.WebKit) {
 Position.cumulativeOffset = function(element) {
  var valueT = 0, valueL = 0;
  do {
   valueT += element.offsetTop || 0;
   valueL += element.offsetLeft || 0;
   if (element.offsetParent == document.body)
    if (Element.getStyle(element, 'position') == 'absolute') break;

   element = element.offsetParent;
  } while (element);

  return [valueL, valueT];
 }
}

Element.addMethods();
var Scriptaculous = {
 Version: '1.7.1_beta3',
 require: function(libraryName) {

  
 },
 REQUIRED_PROTOTYPE: '1.5.1',
 load: function() {
  function convertVersionString(versionString){
   var r = versionString.split('.');
   return parseInt(r[0])*100000 + parseInt(r[1])*1000 + parseInt(r[2]);
  }
 
  if((typeof Prototype=='undefined') || 
    (typeof Element == 'undefined') || 
    (typeof Element.Methods=='undefined') ||
    (convertVersionString(Prototype.Version) < 
    convertVersionString(Scriptaculous.REQUIRED_PROTOTYPE)))
    throw("script.aculo.us requires the Prototype JavaScript framework >= " +
    Scriptaculous.REQUIRED_PROTOTYPE);
  
  $A(document.getElementsByTagName("script")).findAll( function(s) {
   return (s.src && s.src.match(/scriptaculous\.js(\?.*)?$/))
  }).each( function(s) {
   var path = s.src.replace(/scriptaculous\.js(\?.*)?$/,'');
   var includes = s.src.match(/\?.*load=([a-z,]*)/);
   (includes ? includes[1] : 'builder,effects,dragdrop,controls,slider,sound').split(',').each(
    function(include) { Scriptaculous.require(path+include+'.js') });
  });
 }
}

Scriptaculous.load();








var Builder = {
 NODEMAP: {
  AREA: 'map',
  CAPTION: 'table',
  COL: 'table',
  COLGROUP: 'table',
  LEGEND: 'fieldset',
  OPTGROUP: 'select',
  OPTION: 'select',
  PARAM: 'object',
  TBODY: 'table',
  TD: 'table',
  TFOOT: 'table',
  TH: 'table',
  THEAD: 'table',
  TR: 'table'
 },

 node: function(elementName) {
  elementName = elementName.toUpperCase();
  
  
  var parentTag = this.NODEMAP[elementName] || 'div';
  var parentElement = document.createElement(parentTag);
  try { 
   parentElement.innerHTML = "<" + elementName + "></" + elementName + ">";
  } catch(e) {}
  var element = parentElement.firstChild || null;
   
  
  if(element && (element.tagName.toUpperCase() != elementName))
   element = element.getElementsByTagName(elementName)[0];
  
  
  if(!element) element = document.createElement(elementName);
  
  
  if(!element) return;

  
  if(arguments[1])
   if(this._isStringOrNumber(arguments[1]) ||
    (arguments[1] instanceof Array) ||
    arguments[1].tagName) {
     this._children(element, arguments[1]);
    } else {
     var attrs = this._attributes(arguments[1]);
     if(attrs.length) {
      try { 
       parentElement.innerHTML = "<" +elementName + " " +
        attrs + "></" + elementName + ">";
      } catch(e) {}
      element = parentElement.firstChild || null;
      
      if(!element) {
       element = document.createElement(elementName);
       for(attr in arguments[1]) 
        element[attr == 'class' ? 'className' : attr] = arguments[1][attr];
      }
      if(element.tagName.toUpperCase() != elementName)
       element = parentElement.getElementsByTagName(elementName)[0];
     }
    } 

  
  if(arguments[2])
   this._children(element, arguments[2]);

   return element;
 },
 _text: function(text) {
   return document.createTextNode(text);
 },

 ATTR_MAP: {
  'className': 'class',
  'htmlFor': 'for'
 },

 _attributes: function(attributes) {
  var attrs = [];
  for(attribute in attributes)
   attrs.push((attribute in this.ATTR_MAP ? this.ATTR_MAP[attribute] : attribute) +
     '="' + attributes[attribute].toString().escapeHTML().gsub(/"/,'&quot;') + '"');
  return attrs.join(" ");
 },
 _children: function(element, children) {
  if(children.tagName) {
   element.appendChild(children);
   return;
  }
  if(typeof children=='object') { 
   children.flatten().each( function(e) {
    if(typeof e=='object')
     element.appendChild(e)
    else
     if(Builder._isStringOrNumber(e))
      element.appendChild(Builder._text(e));
   });
  } else
   if(Builder._isStringOrNumber(children))
    element.appendChild(Builder._text(children));
 },
 _isStringOrNumber: function(param) {
  return(typeof param=='string' || typeof param=='number');
 },
 build: function(html) {
  var element = this.node('div');
  $(element).update(html.strip());
  return element.down();
 },
 dump: function(scope) { 
  if(typeof scope != 'object' && typeof scope != 'function') scope = window; 
 
  var tags = ("A ABBR ACRONYM ADDRESS APPLET AREA B BASE BASEFONT BDO BIG BLOCKQUOTE BODY " +
   "BR BUTTON CAPTION CENTER CITE CODE COL COLGROUP DD DEL DFN DIR DIV DL DT EM FIELDSET " +
   "FONT FORM FRAME FRAMESET H1 H2 H3 H4 H5 H6 HEAD HR HTML I IFRAME IMG INPUT INS ISINDEX "+
   "KBD LABEL LEGEND LI LINK MAP MENU META NOFRAMES NOSCRIPT OBJECT OL OPTGROUP OPTION P "+
   "PARAM PRE Q S SAMP SCRIPT SELECT SMALL SPAN STRIKE STRONG STYLE SUB SUP TABLE TBODY TD "+
   "TEXTAREA TFOOT TH THEAD TITLE TR TT U UL VAR").split(/\s+/);
 
  tags.each( function(tag){ 
   scope[tag] = function() { 
    return Builder.node.apply(Builder, [tag].concat($A(arguments))); 
   } 
  });
 }
}


String.prototype.parseColor = function() { 
 var color = '#';
 if(this.slice(0,4) == 'rgb(') { 
  var cols = this.slice(4,this.length-1).split(','); 
  var i=0; do { color += parseInt(cols[i]).toColorPart() } while (++i<3); 
 } else { 
  if(this.slice(0,1) == '#') { 
   if(this.length==4) for(var i=1;i<4;i++) color += (this.charAt(i) + this.charAt(i)).toLowerCase(); 
   if(this.length==7) color = this.toLowerCase(); 
  } 
 } 
 return(color.length==7 ? color : (arguments[0] || this)); 
}

/*--------------------------------------------------------------------------*/

Element.collectTextNodes = function(element) { 
 return $A($(element).childNodes).collect( function(node) {
  return (node.nodeType==3 ? node.nodeValue : 
   (node.hasChildNodes() ? Element.collectTextNodes(node) : ''));
 }).flatten().join('');
}

Element.collectTextNodesIgnoreClass = function(element, className) { 
 return $A($(element).childNodes).collect( function(node) {
  return (node.nodeType==3 ? node.nodeValue : 
   ((node.hasChildNodes() && !Element.hasClassName(node,className)) ? 
    Element.collectTextNodesIgnoreClass(node, className) : ''));
 }).flatten().join('');
}

Element.setContentZoom = function(element, percent) {
 element = $(element); 
 element.setStyle({fontSize: (percent/100) + 'em'});  
 if(Prototype.Browser.WebKit) window.scrollBy(0,0);
 return element;
}

Element.getInlineOpacity = function(element){
 return $(element).style.opacity || '';
}

Element.forceRerendering = function(element) {
 try {
  element = $(element);
  var n = document.createTextNode(' ');
  element.appendChild(n);
  element.removeChild(n);
 } catch(e) { }
};

/*--------------------------------------------------------------------------*/

Array.prototype.call = function() {
 var args = arguments;
 this.each(function(f){ f.apply(this, args) });
}

/*--------------------------------------------------------------------------*/

var Effect = {
 _elementDoesNotExistError: {
  name: 'ElementDoesNotExistError',
  message: 'The specified DOM element does not exist, but is required for this effect to operate'
 },
 tagifyText: function(element) {
  if(typeof Builder == 'undefined')
   throw("Effect.tagifyText requires including script.aculo.us' builder.js library");
   
  var tagifyStyle = 'position:relative';
  if(Prototype.Browser.IE) tagifyStyle += ';zoom:1';
  
  element = $(element);
  $A(element.childNodes).each( function(child) {
   if(child.nodeType==3) {
    child.nodeValue.toArray().each( function(character) {
     element.insertBefore(
      Builder.node('span',{style: tagifyStyle},
       character == ' ' ? String.fromCharCode(160) : character), 
       child);
    });
    Element.remove(child);
   }
  });
 },
 multiple: function(element, effect) {
  var elements;
  if(((typeof element == 'object') || 
    (typeof element == 'function')) && 
    (element.length))
   elements = element;
  else
   elements = $(element).childNodes;
   
  var options = Object.extend({
   speed: 0.1,
   delay: 0.0
  }, arguments[2] || {});
  var masterDelay = options.delay;

  $A(elements).each( function(element, index) {
   new effect(element, Object.extend(options, { delay: index * options.speed + masterDelay }));
  });
 },
 PAIRS: {
  'slide': ['SlideDown','SlideUp'],
  'blind': ['BlindDown','BlindUp'],
  'appear': ['Appear','Fade']
 },
 toggle: function(element, effect) {
  element = $(element);
  effect = (effect || 'appear').toLowerCase();
  var options = Object.extend({
   queue: { position:'end', scope:(element.id || 'global'), limit: 1 }
  }, arguments[2] || {});
  Effect[element.visible() ? 
   Effect.PAIRS[effect][1] : Effect.PAIRS[effect][0]](element, options);
 }
};

var Effect2 = Effect; 

/* ------------- transitions ------------- */

Effect.Transitions = {
 linear: Prototype.K,
 sinoidal: function(pos) {
  return (-Math.cos(pos*Math.PI)/2) + 0.5;
 },
 reverse: function(pos) {
  return 1-pos;
 },
 flicker: function(pos) {
  var pos = ((-Math.cos(pos*Math.PI)/4) + 0.75) + Math.random()/4;
  return (pos > 1 ? 1 : pos);
 },
 wobble: function(pos) {
  return (-Math.cos(pos*Math.PI*(9*pos))/2) + 0.5;
 },
 pulse: function(pos, pulses) { 
  pulses = pulses || 5; 
  return (
   Math.round((pos % (1/pulses)) * pulses) == 0 ? 
      ((pos * pulses * 2) - Math.floor(pos * pulses * 2)) : 
    1 - ((pos * pulses * 2) - Math.floor(pos * pulses * 2))
   );
 },
 none: function(pos) {
  return 0;
 },
 full: function(pos) {
  return 1;
 }
};

/* ------------- core effects ------------- */

Effect.ScopedQueue = Class.create();
Object.extend(Object.extend(Effect.ScopedQueue.prototype, Enumerable), {
 initialize: function() {
  this.effects = [];
  this.interval = null;  
 },
 _each: function(iterator) {
  this.effects._each(iterator);
 },
 add: function(effect) {
  var timestamp = new Date().getTime();
  
  var position = (typeof effect.options.queue == 'string') ? 
   effect.options.queue : effect.options.queue.position;
  
  switch(position) {
   case 'front':
    
    this.effects.findAll(function(e){ return e.state=='idle' }).each( function(e) {
      e.startOn += effect.finishOn;
      e.finishOn += effect.finishOn;
     });
    break;
   case 'with-last':
    timestamp = this.effects.pluck('startOn').max() || timestamp;
    break;
   case 'end':
    
    timestamp = this.effects.pluck('finishOn').max() || timestamp;
    break;
  }
  
  effect.startOn += timestamp;
  effect.finishOn += timestamp;

  if(!effect.options.queue.limit || (this.effects.length < effect.options.queue.limit))
   this.effects.push(effect);
  
  if(!this.interval)
   this.interval = setInterval(this.loop.bind(this), 15);
 },
 remove: function(effect) {
  this.effects = this.effects.reject(function(e) { return e==effect });
  if(this.effects.length == 0) {
   clearInterval(this.interval);
   this.interval = null;
  }
 },
 loop: function() {
  var timePos = new Date().getTime();
  for(var i=0, len=this.effects.length;i<len;i++) 
   this.effects[i] && this.effects[i].loop(timePos);
 }
});

Effect.Queues = {
 instances: $H(),
 get: function(queueName) {
  if(typeof queueName != 'string') return queueName;
  
  if(!this.instances[queueName])
   this.instances[queueName] = new Effect.ScopedQueue();
   
  return this.instances[queueName];
 }
}
Effect.Queue = Effect.Queues.get('global');

Effect.DefaultOptions = {
 transition: Effect.Transitions.sinoidal,
 duration:  1.0,  
 fps:    100,  
 sync:    false, 
 from:    0.0,
 to:     1.0,
 delay:   0.0,
 queue:   'parallel'
}

Effect.Base = function() {};
Effect.Base.prototype = {
 position: null,
 start: function(options) {
  function codeForEvent(options,eventName){
   return (
    (options[eventName+'Internal'] ? 'this.options.'+eventName+'Internal(this);' : '') +
    (options[eventName] ? 'this.options.'+eventName+'(this);' : '')
   );
  }
  if(options.transition === false) options.transition = Effect.Transitions.linear;
  this.options   = Object.extend(Object.extend({},Effect.DefaultOptions), options || {});
  this.currentFrame = 0;
  this.state    = 'idle';
  this.startOn   = this.options.delay*1000;
  this.finishOn   = this.startOn+(this.options.duration*1000);
  this.fromToDelta = this.options.to-this.options.from;
  this.totalTime  = this.finishOn-this.startOn;
  this.totalFrames = this.options.fps*this.options.duration;
  
  eval('this.render = function(pos){ '+
   'if(this.state=="idle"){this.state="running";'+
   codeForEvent(options,'beforeSetup')+
   (this.setup ? 'this.setup();':'')+ 
   codeForEvent(options,'afterSetup')+
   '};if(this.state=="running"){'+
   'pos=this.options.transition(pos)*'+this.fromToDelta+'+'+this.options.from+';'+
   'this.position=pos;'+
   codeForEvent(options,'beforeUpdate')+
   (this.update ? 'this.update(pos);':'')+
   codeForEvent(options,'afterUpdate')+
   '}}');
  
  this.event('beforeStart');
  if(!this.options.sync)
   Effect.Queues.get(typeof this.options.queue == 'string' ? 
    'global' : this.options.queue.scope).add(this);
 },
 loop: function(timePos) {
  if(timePos >= this.startOn) {
   if(timePos >= this.finishOn) {
    this.render(1.0);
    this.cancel();
    this.event('beforeFinish');
    if(this.finish) this.finish(); 
    this.event('afterFinish');
    return; 
   }
   var pos  = (timePos - this.startOn) / this.totalTime,
     frame = Math.round(pos * this.totalFrames);
   if(frame > this.currentFrame) {
    this.render(pos);
    this.currentFrame = frame;
   }
  }
 },
 cancel: function() {
  if(!this.options.sync)
   Effect.Queues.get(typeof this.options.queue == 'string' ? 
    'global' : this.options.queue.scope).remove(this);
  this.state = 'finished';
 },
 event: function(eventName) {
  if(this.options[eventName + 'Internal']) this.options[eventName + 'Internal'](this);
  if(this.options[eventName]) this.options[eventName](this);
 },
 inspect: function() {
  var data = $H();
  for(property in this)
   if(typeof this[property] != 'function') data[property] = this[property];
  return '#<Effect:' + data.inspect() + ',options:' + $H(this.options).inspect() + '>';
 }
}

Effect.Parallel = Class.create();
Object.extend(Object.extend(Effect.Parallel.prototype, Effect.Base.prototype), {
 initialize: function(effects) {
  this.effects = effects || [];
  this.start(arguments[1]);
 },
 update: function(position) {
  this.effects.invoke('render', position);
 },
 finish: function(position) {
  this.effects.each( function(effect) {
   effect.render(1.0);
   effect.cancel();
   effect.event('beforeFinish');
   if(effect.finish) effect.finish(position);
   effect.event('afterFinish');
  });
 }
});

Effect.Event = Class.create();
Object.extend(Object.extend(Effect.Event.prototype, Effect.Base.prototype), {
 initialize: function() {
  var options = Object.extend({
   duration: 0
  }, arguments[0] || {});
  this.start(options);
 },
 update: Prototype.emptyFunction
});

Effect.Opacity = Class.create();
Object.extend(Object.extend(Effect.Opacity.prototype, Effect.Base.prototype), {
 initialize: function(element) {
  this.element = $(element);
  if(!this.element) throw(Effect._elementDoesNotExistError);
  
  if(Prototype.Browser.IE && (!this.element.currentStyle.hasLayout))
   this.element.setStyle({zoom: 1});
  var options = Object.extend({
   from: this.element.getOpacity() || 0.0,
   to:  1.0
  }, arguments[1] || {});
  this.start(options);
 },
 update: function(position) {
  this.element.setOpacity(position);
 }
});

Effect.Move = Class.create();
Object.extend(Object.extend(Effect.Move.prototype, Effect.Base.prototype), {
 initialize: function(element) {
  this.element = $(element);
  if(!this.element) throw(Effect._elementDoesNotExistError);
  var options = Object.extend({
   x:  0,
   y:  0,
   mode: 'relative'
  }, arguments[1] || {});
  this.start(options);
 },
 setup: function() {
  
  this.element.makePositioned();
  this.originalLeft = parseFloat(this.element.getStyle('left') || '0');
  this.originalTop = parseFloat(this.element.getStyle('top') || '0');
  if(this.options.mode == 'absolute') {
   
   this.options.x = this.options.x - this.originalLeft;
   this.options.y = this.options.y - this.originalTop;
  }
 },
 update: function(position) {
  this.element.setStyle({
   left: Math.round(this.options.x * position + this.originalLeft) + 'px',
   top: Math.round(this.options.y * position + this.originalTop) + 'px'
  });
 }
});


Effect.MoveBy = function(element, toTop, toLeft) {
 return new Effect.Move(element, 
  Object.extend({ x: toLeft, y: toTop }, arguments[3] || {}));
};

Effect.Scale = Class.create();
Object.extend(Object.extend(Effect.Scale.prototype, Effect.Base.prototype), {
 initialize: function(element, percent) {
  this.element = $(element);
  if(!this.element) throw(Effect._elementDoesNotExistError);
  var options = Object.extend({
   scaleX: true,
   scaleY: true,
   scaleContent: true,
   scaleFromCenter: false,
   scaleMode: 'box',    
   scaleFrom: 100.0,
   scaleTo:  percent
  }, arguments[2] || {});
  this.start(options);
 },
 setup: function() {
  this.restoreAfterFinish = this.options.restoreAfterFinish || false;
  this.elementPositioning = this.element.getStyle('position');
  
  this.originalStyle = {};
  ['top','left','width','height','fontSize'].each( function(k) {
   this.originalStyle[k] = this.element.style[k];
  }.bind(this));
   
  this.originalTop = this.element.offsetTop;
  this.originalLeft = this.element.offsetLeft;
  
  var fontSize = this.element.getStyle('font-size') || '100%';
  ['em','px','%','pt'].each( function(fontSizeType) {
   if(fontSize.indexOf(fontSizeType)>0) {
    this.fontSize   = parseFloat(fontSize);
    this.fontSizeType = fontSizeType;
   }
  }.bind(this));
  
  this.factor = (this.options.scaleTo - this.options.scaleFrom)/100;
  
  this.dims = null;
  if(this.options.scaleMode=='box')
   this.dims = [this.element.offsetHeight, this.element.offsetWidth];
  if(/^content/.test(this.options.scaleMode))
   this.dims = [this.element.scrollHeight, this.element.scrollWidth];
  if(!this.dims)
   this.dims = [this.options.scaleMode.originalHeight,
          this.options.scaleMode.originalWidth];
 },
 update: function(position) {
  var currentScale = (this.options.scaleFrom/100.0) + (this.factor * position);
  if(this.options.scaleContent && this.fontSize)
   this.element.setStyle({fontSize: this.fontSize * currentScale + this.fontSizeType });
  this.setDimensions(this.dims[0] * currentScale, this.dims[1] * currentScale);
 },
 finish: function(position) {
  if(this.restoreAfterFinish) this.element.setStyle(this.originalStyle);
 },
 setDimensions: function(height, width) {
  var d = {};
  if(this.options.scaleX) d.width = Math.round(width) + 'px';
  if(this.options.scaleY) d.height = Math.round(height) + 'px';
  if(this.options.scaleFromCenter) {
   var topd = (height - this.dims[0])/2;
   var leftd = (width - this.dims[1])/2;
   if(this.elementPositioning == 'absolute') {
    if(this.options.scaleY) d.top = this.originalTop-topd + 'px';
    if(this.options.scaleX) d.left = this.originalLeft-leftd + 'px';
   } else {
    if(this.options.scaleY) d.top = -topd + 'px';
    if(this.options.scaleX) d.left = -leftd + 'px';
   }
  }
  this.element.setStyle(d);
 }
});

Effect.Highlight = Class.create();
Object.extend(Object.extend(Effect.Highlight.prototype, Effect.Base.prototype), {
 initialize: function(element) {
  this.element = $(element);
  if(!this.element) throw(Effect._elementDoesNotExistError);
  var options = Object.extend({ startcolor: '#ffff99' }, arguments[1] || {});
  this.start(options);
 },
 setup: function() {
  
  if(this.element.getStyle('display')=='none') { this.cancel(); return; }
  
  this.oldStyle = {};
  if (!this.options.keepBackgroundImage) {
   this.oldStyle.backgroundImage = this.element.getStyle('background-image');
   this.element.setStyle({backgroundImage: 'none'});
  }
  if(!this.options.endcolor)
   this.options.endcolor = this.element.getStyle('background-color').parseColor('#ffffff');
  if(!this.options.restorecolor)
   this.options.restorecolor = this.element.getStyle('background-color');
  
  this._base = $R(0,2).map(function(i){ return parseInt(this.options.startcolor.slice(i*2+1,i*2+3),16) }.bind(this));
  this._delta = $R(0,2).map(function(i){ return parseInt(this.options.endcolor.slice(i*2+1,i*2+3),16)-this._base[i] }.bind(this));
 },
 update: function(position) {
  this.element.setStyle({backgroundColor: $R(0,2).inject('#',function(m,v,i){
   return m+(Math.round(this._base[i]+(this._delta[i]*position)).toColorPart()); }.bind(this)) });
 },
 finish: function() {
  this.element.setStyle(Object.extend(this.oldStyle, {
   backgroundColor: this.options.restorecolor
  }));
 }
});

Effect.ScrollTo = Class.create();
Object.extend(Object.extend(Effect.ScrollTo.prototype, Effect.Base.prototype), {
 initialize: function(element) {
  this.element = $(element);
  this.start(arguments[1] || {});
 },
 setup: function() {
  Position.prepare();
  var offsets = Position.cumulativeOffset(this.element);
  if(this.options.offset) offsets[1] += this.options.offset;
  var max = window.innerHeight ? 
   window.height - window.innerHeight :
   document.body.scrollHeight - 
    (document.documentElement.clientHeight ? 
     document.documentElement.clientHeight : document.body.clientHeight);
  this.scrollStart = Position.deltaY;
  this.delta = (offsets[1] > max ? max : offsets[1]) - this.scrollStart;
 },
 update: function(position) {
  Position.prepare();
  window.scrollTo(Position.deltaX, 
   this.scrollStart + (position*this.delta));
 }
});

/* ------------- combination effects ------------- */

Effect.Fade = function(element) {
 element = $(element);
 var oldOpacity = element.getInlineOpacity();
 var options = Object.extend({
 from: element.getOpacity() || 1.0,
 to:  0.0,
 afterFinishInternal: function(effect) { 
  if(effect.options.to!=0) return;
  effect.element.hide().setStyle({opacity: oldOpacity}); 
 }}, arguments[1] || {});
 return new Effect.Opacity(element,options);
}

Effect.Appear = function(element) {
 element = $(element);
 var options = Object.extend({
 from: (element.getStyle('display') == 'none' ? 0.0 : element.getOpacity() || 0.0),
 to:  1.0,
 
 afterFinishInternal: function(effect) {
  effect.element.forceRerendering();
 },
 beforeSetup: function(effect) {
  effect.element.setOpacity(effect.options.from).show(); 
 }}, arguments[1] || {});
 return new Effect.Opacity(element,options);
}

Effect.Puff = function(element) {
 element = $(element);
 var oldStyle = { 
  opacity: element.getInlineOpacity(), 
  position: element.getStyle('position'),
  top: element.style.top,
  left: element.style.left,
  width: element.style.width,
  height: element.style.height
 };
 return new Effect.Parallel(
  [ new Effect.Scale(element, 200, 
   { sync: true, scaleFromCenter: true, scaleContent: true, restoreAfterFinish: true }), 
   new Effect.Opacity(element, { sync: true, to: 0.0 } ) ], 
   Object.extend({ duration: 1.0, 
   beforeSetupInternal: function(effect) {
    Position.absolutize(effect.effects[0].element)
   },
   afterFinishInternal: function(effect) {
     effect.effects[0].element.hide().setStyle(oldStyle); }
   }, arguments[1] || {})
  );
}

Effect.BlindUp = function(element) {
 element = $(element);
 element.makeClipping();
 return new Effect.Scale(element, 0,
  Object.extend({ scaleContent: false, 
   scaleX: false, 
   restoreAfterFinish: true,
   afterFinishInternal: function(effect) {
    effect.element.hide().undoClipping();
   } 
  }, arguments[1] || {})
 );
}

Effect.BlindDown = function(element) {
 element = $(element);
 var elementDimensions = element.getDimensions();
 return new Effect.Scale(element, 100, Object.extend({ 
  scaleContent: false, 
  scaleX: false,
  scaleFrom: 0,
  scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
  restoreAfterFinish: true,
  afterSetup: function(effect) {
   effect.element.makeClipping().setStyle({height: '0px'}).show(); 
  }, 
  afterFinishInternal: function(effect) {
   effect.element.undoClipping();
  }
 }, arguments[1] || {}));
}

Effect.SwitchOff = function(element) {
 element = $(element);
 var oldOpacity = element.getInlineOpacity();
 return new Effect.Appear(element, Object.extend({
  duration: 0.4,
  from: 0,
  transition: Effect.Transitions.flicker,
  afterFinishInternal: function(effect) {
   new Effect.Scale(effect.element, 1, { 
    duration: 0.3, scaleFromCenter: true,
    scaleX: false, scaleContent: false, restoreAfterFinish: true,
    beforeSetup: function(effect) { 
     effect.element.makePositioned().makeClipping();
    },
    afterFinishInternal: function(effect) {
     effect.element.hide().undoClipping().undoPositioned().setStyle({opacity: oldOpacity});
    }
   })
  }
 }, arguments[1] || {}));
}

Effect.DropOut = function(element) {
 element = $(element);
 var oldStyle = {
  top: element.getStyle('top'),
  left: element.getStyle('left'),
  opacity: element.getInlineOpacity() };
 return new Effect.Parallel(
  [ new Effect.Move(element, {x: 0, y: 100, sync: true }), 
   new Effect.Opacity(element, { sync: true, to: 0.0 }) ],
  Object.extend(
   { duration: 0.5,
    beforeSetup: function(effect) {
     effect.effects[0].element.makePositioned(); 
    },
    afterFinishInternal: function(effect) {
     effect.effects[0].element.hide().undoPositioned().setStyle(oldStyle);
    } 
   }, arguments[1] || {}));
}

Effect.Shake = function(element) {
 element = $(element);
 var oldStyle = {
  top: element.getStyle('top'),
  left: element.getStyle('left') };
  return new Effect.Move(element, 
   { x: 20, y: 0, duration: 0.05, afterFinishInternal: function(effect) {
  new Effect.Move(effect.element,
   { x: -40, y: 0, duration: 0.1, afterFinishInternal: function(effect) {
  new Effect.Move(effect.element,
   { x: 40, y: 0, duration: 0.1, afterFinishInternal: function(effect) {
  new Effect.Move(effect.element,
   { x: -40, y: 0, duration: 0.1, afterFinishInternal: function(effect) {
  new Effect.Move(effect.element,
   { x: 40, y: 0, duration: 0.1, afterFinishInternal: function(effect) {
  new Effect.Move(effect.element,
   { x: -20, y: 0, duration: 0.05, afterFinishInternal: function(effect) {
    effect.element.undoPositioned().setStyle(oldStyle);
 }}) }}) }}) }}) }}) }});
}

Effect.SlideDown = function(element) {
 element = $(element).cleanWhitespace();
 
 var oldInnerBottom = element.down().getStyle('bottom');
 var elementDimensions = element.getDimensions();
 return new Effect.Scale(element, 100, Object.extend({ 
  scaleContent: false, 
  scaleX: false, 
  scaleFrom: window.opera ? 0 : 1,
  scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
  restoreAfterFinish: true,
  afterSetup: function(effect) {
   effect.element.makePositioned();
   effect.element.down().makePositioned();
   if(window.opera) effect.element.setStyle({top: ''});
   effect.element.makeClipping().setStyle({height: '0px'}).show(); 
  },
  afterUpdateInternal: function(effect) {
  
  //UPDATED UNDER LINE -- ADD TRY
  
  try{
  	effect.element.down().setStyle({bottom:
    (effect.dims[0] - effect.element.clientHeight) + 'px' }); 
  }catch(ee){}
  
  },
  afterFinishInternal: function(effect) {
   effect.element.undoClipping().undoPositioned();
   effect.element.down().undoPositioned().setStyle({bottom: oldInnerBottom}); }
  }, arguments[1] || {})
 );
}

Effect.SlideUp = function(element) {
 element = $(element).cleanWhitespace();
 var oldInnerBottom = element.down().getStyle('bottom');
 return new Effect.Scale(element, window.opera ? 0 : 1,
  Object.extend({ scaleContent: false, 
  scaleX: false, 
  scaleMode: 'box',
  scaleFrom: 100,
  restoreAfterFinish: true,
  beforeStartInternal: function(effect) {
   effect.element.makePositioned();
   effect.element.down().makePositioned();
   if(window.opera) effect.element.setStyle({top: ''});
   effect.element.makeClipping().show();
  }, 
  afterUpdateInternal: function(effect) {
   effect.element.down().setStyle({bottom:
    (effect.dims[0] - effect.element.clientHeight) + 'px' });
  },
  afterFinishInternal: function(effect) {
   effect.element.hide().undoClipping().undoPositioned().setStyle({bottom: oldInnerBottom});
   effect.element.down().undoPositioned();
  }
  }, arguments[1] || {})
 );
}


Effect.Squish = function(element) {
 return new Effect.Scale(element, window.opera ? 1 : 0, { 
  restoreAfterFinish: true,
  beforeSetup: function(effect) {
   effect.element.makeClipping(); 
  }, 
  afterFinishInternal: function(effect) {
   effect.element.hide().undoClipping(); 
  }
 });
}

Effect.Grow = function(element) {
 element = $(element);
 var options = Object.extend({
  direction: 'center',
  moveTransition: Effect.Transitions.sinoidal,
  scaleTransition: Effect.Transitions.sinoidal,
  opacityTransition: Effect.Transitions.full
 }, arguments[1] || {});
 var oldStyle = {
  top: element.style.top,
  left: element.style.left,
  height: element.style.height,
  width: element.style.width,
  opacity: element.getInlineOpacity() };

 var dims = element.getDimensions();  
 var initialMoveX, initialMoveY;
 var moveX, moveY;
 
 switch (options.direction) {
  case 'top-left':
   initialMoveX = initialMoveY = moveX = moveY = 0; 
   break;
  case 'top-right':
   initialMoveX = dims.width;
   initialMoveY = moveY = 0;
   moveX = -dims.width;
   break;
  case 'bottom-left':
   initialMoveX = moveX = 0;
   initialMoveY = dims.height;
   moveY = -dims.height;
   break;
  case 'bottom-right':
   initialMoveX = dims.width;
   initialMoveY = dims.height;
   moveX = -dims.width;
   moveY = -dims.height;
   break;
  case 'center':
   initialMoveX = dims.width / 2;
   initialMoveY = dims.height / 2;
   moveX = -dims.width / 2;
   moveY = -dims.height / 2;
   break;
 }
 
 return new Effect.Move(element, {
  x: initialMoveX,
  y: initialMoveY,
  duration: 0.01, 
  beforeSetup: function(effect) {
   effect.element.hide().makeClipping().makePositioned();
  },
  afterFinishInternal: function(effect) {
   new Effect.Parallel(
    [ new Effect.Opacity(effect.element, { sync: true, to: 1.0, from: 0.0, transition: options.opacityTransition }),
     new Effect.Move(effect.element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition }),
     new Effect.Scale(effect.element, 100, {
      scaleMode: { originalHeight: dims.height, originalWidth: dims.width }, 
      sync: true, scaleFrom: window.opera ? 1 : 0, transition: options.scaleTransition, restoreAfterFinish: true})
    ], Object.extend({
       beforeSetup: function(effect) {
        effect.effects[0].element.setStyle({height: '0px'}).show(); 
       },
       afterFinishInternal: function(effect) {
        effect.effects[0].element.undoClipping().undoPositioned().setStyle(oldStyle); 
       }
      }, options)
   )
  }
 });
}

Effect.Shrink = function(element) {
 element = $(element);
 var options = Object.extend({
  direction: 'center',
  moveTransition: Effect.Transitions.sinoidal,
  scaleTransition: Effect.Transitions.sinoidal,
  opacityTransition: Effect.Transitions.none
 }, arguments[1] || {});
 var oldStyle = {
  top: element.style.top,
  left: element.style.left,
  height: element.style.height,
  width: element.style.width,
  opacity: element.getInlineOpacity() };

 var dims = element.getDimensions();
 var moveX, moveY;
 
 switch (options.direction) {
  case 'top-left':
   moveX = moveY = 0;
   break;
  case 'top-right':
   moveX = dims.width;
   moveY = 0;
   break;
  case 'bottom-left':
   moveX = 0;
   moveY = dims.height;
   break;
  case 'bottom-right':
   moveX = dims.width;
   moveY = dims.height;
   break;
  case 'center': 
   moveX = dims.width / 2;
   moveY = dims.height / 2;
   break;
 }
 
 return new Effect.Parallel(
  [ new Effect.Opacity(element, { sync: true, to: 0.0, from: 1.0, transition: options.opacityTransition }),
   new Effect.Scale(element, window.opera ? 1 : 0, { sync: true, transition: options.scaleTransition, restoreAfterFinish: true}),
   new Effect.Move(element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition })
  ], Object.extend({      
     beforeStartInternal: function(effect) {
      effect.effects[0].element.makePositioned().makeClipping(); 
     },
     afterFinishInternal: function(effect) {
      effect.effects[0].element.hide().undoClipping().undoPositioned().setStyle(oldStyle); }
    }, options)
 );
}

Effect.Pulsate = function(element) {
 element = $(element);
 var options  = arguments[1] || {};
 var oldOpacity = element.getInlineOpacity();
 var transition = options.transition || Effect.Transitions.sinoidal;
 var reverser  = function(pos){ return transition(1-Effect.Transitions.pulse(pos, options.pulses)) };
 reverser.bind(transition);
 return new Effect.Opacity(element, 
  Object.extend(Object.extend({ duration: 2.0, from: 0,
   afterFinishInternal: function(effect) { effect.element.setStyle({opacity: oldOpacity}); }
  }, options), {transition: reverser}));
}

Effect.Fold = function(element) {
 element = $(element);
 var oldStyle = {
  top: element.style.top,
  left: element.style.left,
  width: element.style.width,
  height: element.style.height };
 element.makeClipping();
 return new Effect.Scale(element, 5, Object.extend({  
  scaleContent: false,
  scaleX: false,
  afterFinishInternal: function(effect) {
  new Effect.Scale(element, 1, { 
   scaleContent: false, 
   scaleY: false,
   afterFinishInternal: function(effect) {
    effect.element.hide().undoClipping().setStyle(oldStyle);
   } });
 }}, arguments[1] || {}));
};

Effect.Morph = Class.create();
Object.extend(Object.extend(Effect.Morph.prototype, Effect.Base.prototype), {
 initialize: function(element) {
  this.element = $(element);
  if(!this.element) throw(Effect._elementDoesNotExistError);
  var options = Object.extend({
   style: {}
  }, arguments[1] || {});
  if (typeof options.style == 'string') {
   if(options.style.indexOf(':') == -1) {
    var cssText = '', selector = '.' + options.style;
    $A(document.styleSheets).reverse().each(function(styleSheet) {
     if (styleSheet.cssRules) cssRules = styleSheet.cssRules;
     else if (styleSheet.rules) cssRules = styleSheet.rules;
     $A(cssRules).reverse().each(function(rule) {
      if (selector == rule.selectorText) {
       cssText = rule.style.cssText;
       throw $break;
      }
     });
     if (cssText) throw $break;
    });
    this.style = cssText.parseStyle();
    options.afterFinishInternal = function(effect){
     effect.element.addClassName(effect.options.style);
     effect.transforms.each(function(transform) {
      if(transform.style != 'opacity')
       effect.element.style[transform.style] = '';
     });
    }
   } else this.style = options.style.parseStyle();
  } else this.style = $H(options.style)
  this.start(options);
 },
 setup: function(){
  function parseColor(color){
   if(!color || ['rgba(0, 0, 0, 0)','transparent'].include(color)) color = '#ffffff';
   color = color.parseColor();
   return $R(0,2).map(function(i){
    return parseInt( color.slice(i*2+1,i*2+3), 16 ) 
   });
  }
  this.transforms = this.style.map(function(pair){
   var property = pair[0], value = pair[1], unit = null;

   if(value.parseColor('#zzzzzz') != '#zzzzzz') {
    value = value.parseColor();
    unit = 'color';
   } else if(property == 'opacity') {
    value = parseFloat(value);
    if(Prototype.Browser.IE && (!this.element.currentStyle.hasLayout))
     this.element.setStyle({zoom: 1});
   } else if(Element.CSS_LENGTH.test(value)) {
     var components = value.match(/^([\+\-]?[0-9\.]+)(.*)$/);
     value = parseFloat(components[1]);
     unit = (components.length == 3) ? components[2] : null;
   }

   var originalValue = this.element.getStyle(property);
   return { 
    style: property.camelize(), 
    originalValue: unit=='color' ? parseColor(originalValue) : parseFloat(originalValue || 0), 
    targetValue: unit=='color' ? parseColor(value) : value,
    unit: unit
   };
  }.bind(this)).reject(function(transform){
   return (
    (transform.originalValue == transform.targetValue) ||
    (
     transform.unit != 'color' &&
     (isNaN(transform.originalValue) || isNaN(transform.targetValue))
    )
   )
  });
 },
 update: function(position) {
  var style = {}, transform, i = this.transforms.length;
  while(i--)
   style[(transform = this.transforms[i]).style] = 
    transform.unit=='color' ? '#'+
     (Math.round(transform.originalValue[0]+
      (transform.targetValue[0]-transform.originalValue[0])*position)).toColorPart() +
     (Math.round(transform.originalValue[1]+
      (transform.targetValue[1]-transform.originalValue[1])*position)).toColorPart() +
     (Math.round(transform.originalValue[2]+
      (transform.targetValue[2]-transform.originalValue[2])*position)).toColorPart() :
    transform.originalValue + Math.round(
     ((transform.targetValue - transform.originalValue) * position) * 1000)/1000 + transform.unit;
  this.element.setStyle(style, true);
 }
});

Effect.Transform = Class.create();
Object.extend(Effect.Transform.prototype, {
 initialize: function(tracks){
  this.tracks = [];
  this.options = arguments[1] || {};
  this.addTracks(tracks);
 },
 addTracks: function(tracks){
  tracks.each(function(track){
   var data = $H(track).values().first();
   this.tracks.push($H({
    ids:   $H(track).keys().first(),
    effect: Effect.Morph,
    options: { style: data }
   }));
  }.bind(this));
  return this;
 },
 play: function(){
  return new Effect.Parallel(
   this.tracks.map(function(track){
    var elements = [$(track.ids) || $$(track.ids)].flatten();
    return elements.map(function(e){ return new track.effect(e, Object.extend({ sync:true }, track.options)) });
   }).flatten(),
   this.options
  );
 }
});

Element.CSS_PROPERTIES = $w(
 'backgroundColor backgroundPosition borderBottomColor borderBottomStyle ' + 
 'borderBottomWidth borderLeftColor borderLeftStyle borderLeftWidth ' +
 'borderRightColor borderRightStyle borderRightWidth borderSpacing ' +
 'borderTopColor borderTopStyle borderTopWidth bottom clip color ' +
 'fontSize fontWeight height left letterSpacing lineHeight ' +
 'marginBottom marginLeft marginRight marginTop markerOffset maxHeight '+
 'maxWidth minHeight minWidth opacity outlineColor outlineOffset ' +
 'outlineWidth paddingBottom paddingLeft paddingRight paddingTop ' +
 'right textIndent top width wordSpacing zIndex');
 
Element.CSS_LENGTH = /^(([\+\-]?[0-9\.]+)(em|ex|px|in|cm|mm|pt|pc|\%))|0$/;

String.prototype.parseStyle = function(){
 var element = document.createElement('div');
 element.innerHTML = '<div style="' + this + '"></div>';
 var style = element.childNodes[0].style, styleRules = $H();
 
 Element.CSS_PROPERTIES.each(function(property){
  if(style[property]) styleRules[property] = style[property]; 
 });
 if(Prototype.Browser.IE && this.indexOf('opacity') > -1) {
  styleRules.opacity = this.match(/opacity:\s*((?:0|1)?(?:\.\d*)?)/)[1];
 }
 return styleRules;
};

Element.morph = function(element, style) {
 new Effect.Morph(element, Object.extend({ style: style }, arguments[2] || {}));
 return element;
};

['getInlineOpacity','forceRerendering','setContentZoom',
 'collectTextNodes','collectTextNodesIgnoreClass','morph'].each( 
 function(f) { Element.Methods[f] = Element[f]; }
);

Element.Methods.visualEffect = function(element, effect, options) {
 s = effect.dasherize().camelize();
 effect_class = s.charAt(0).toUpperCase() + s.substring(1);
 new Effect[effect_class](element, options);
 return $(element);
};

Element.addMethods();

if(typeof Effect == 'undefined')
 throw("controls.js requires including script.aculo.us' effects.js library");

var Autocompleter = {}
Autocompleter.Base = function() {};
Autocompleter.Base.prototype = {
 baseInitialize: function(element, update, options) {
  element     = $(element)
  this.element   = element; 
  this.update   = $(update); 
  this.hasFocus  = false; 
  this.changed   = false; 
  this.active   = false; 
  this.index    = 0;   
  this.entryCount = 0;

  if(this.setOptions)
   this.setOptions(options);
  else
   this.options = options || {};

  this.options.paramName  = this.options.paramName || this.element.name;
  this.options.tokens    = this.options.tokens || [];
  this.options.frequency  = this.options.frequency || 0.4;
  this.options.minChars   = this.options.minChars || 1;
  this.options.onShow    = this.options.onShow || 
   function(element, update){ 
    if(!update.style.position || update.style.position=='absolute') {
     update.style.position = 'absolute';
     Position.clone(element, update, {
      setHeight: false, 
      offsetTop: element.offsetHeight
     });
    }
    Effect.Appear(update,{duration:0.15});
   };
  this.options.onHide = this.options.onHide || 
   function(element, update){ new Effect.Fade(update,{duration:0.15}) };

  if(typeof(this.options.tokens) == 'string') 
   this.options.tokens = new Array(this.options.tokens);

  this.observer = null;
  
  this.element.setAttribute('autocomplete','off');

  Element.hide(this.update);

  Event.observe(this.element, 'blur', this.onBlur.bindAsEventListener(this));
  Event.observe(this.element, 'keypress', this.onKeyPress.bindAsEventListener(this));

  
  Event.observe(window, 'beforeunload', function(){ 
   element.setAttribute('autocomplete', 'on'); 
  });
 },

 show: function() {
  if(Element.getStyle(this.update, 'display')=='none') this.options.onShow(this.element, this.update);
  if(!this.iefix && 
   (Prototype.Browser.IE) &&
   (Element.getStyle(this.update, 'position')=='absolute')) {
   new Insertion.After(this.update, 
    '<iframe id="' + this.update.id + '_iefix" '+
    'style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" ' +
    'src="javascript:false;" frameborder="0" scrolling="no"></iframe>');
   this.iefix = $(this.update.id+'_iefix');
  }
  if(this.iefix) setTimeout(this.fixIEOverlapping.bind(this), 50);
 },
 
 fixIEOverlapping: function() {
  Position.clone(this.update, this.iefix, {setTop:(!this.update.style.height)});
  this.iefix.style.zIndex = 1;
  this.update.style.zIndex = 2;
  Element.show(this.iefix);
 },

 hide: function() {
  this.stopIndicator();
  if(Element.getStyle(this.update, 'display')!='none') this.options.onHide(this.element, this.update);
  if(this.iefix) Element.hide(this.iefix);
 },

 startIndicator: function() {
  if(this.options.indicator) Element.show(this.options.indicator);
 },

 stopIndicator: function() {
  if(this.options.indicator) Element.hide(this.options.indicator);
 },

 onKeyPress: function(event) {
  if(this.active)
   switch(event.keyCode) {
    case Event.KEY_TAB:
    case Event.KEY_RETURN:
     this.selectEntry();
     Event.stop(event);
    case Event.KEY_ESC:
     this.hide();
     this.active = false;
     Event.stop(event);
     return;
    case Event.KEY_LEFT:
    case Event.KEY_RIGHT:
     return;
    case Event.KEY_UP:
     this.markPrevious();
     this.render();
     if(Prototype.Browser.WebKit) Event.stop(event);
     return;
    case Event.KEY_DOWN:
     this.markNext();
     this.render();
     if(Prototype.Browser.WebKit) Event.stop(event);
     return;
   }
   else 
    if(event.keyCode==Event.KEY_TAB || event.keyCode==Event.KEY_RETURN || 
     (Prototype.Browser.WebKit > 0 && event.keyCode == 0)) return;

  this.changed = true;
  this.hasFocus = true;

  if(this.observer) clearTimeout(this.observer);
   this.observer = 
    setTimeout(this.onObserverEvent.bind(this), this.options.frequency*1000);
 },

 activate: function() {
  this.changed = false;
  this.hasFocus = true;
  this.getUpdatedChoices();
 },

 onHover: function(event) {
  var element = Event.findElement(event, 'LI');
  if(this.index != element.autocompleteIndex) 
  {
    this.index = element.autocompleteIndex;
    this.render();
  }
  Event.stop(event);
 },
 
 onClick: function(event) {
  var element = Event.findElement(event, 'LI');
  this.index = element.autocompleteIndex;
  this.selectEntry();
  this.hide();
 },
 
 onBlur: function(event) {
  
  setTimeout(this.hide.bind(this), 250);
  this.hasFocus = false;
  this.active = false;   
 }, 
 
 render: function() {
  if(this.entryCount > 0) {
   for (var i = 0; i < this.entryCount; i++)
    this.index==i ? 
     Element.addClassName(this.getEntry(i),"selected") : 
     Element.removeClassName(this.getEntry(i),"selected");
   if(this.hasFocus) { 
    this.show();
    this.active = true;
   }
  } else {
   this.active = false;
   this.hide();
  }
 },
 
 markPrevious: function() {
  if(this.index > 0) this.index--
   else this.index = this.entryCount-1;
  this.getEntry(this.index).scrollIntoView(true);
 },
 
 markNext: function() {
  if(this.index < this.entryCount-1) this.index++
   else this.index = 0;
  this.getEntry(this.index).scrollIntoView(false);
 },
 
 getEntry: function(index) {
  return this.update.firstChild.childNodes[index];
 },
 
 getCurrentEntry: function() {
  return this.getEntry(this.index);
 },
 
 selectEntry: function() {
  this.active = false;
  this.updateElement(this.getCurrentEntry());
 },

 updateElement: function(selectedElement) {
  if (this.options.updateElement) {
   this.options.updateElement(selectedElement);
   return;
  }
  var value = '';
  if (this.options.select) {
   var nodes = document.getElementsByClassName(this.options.select, selectedElement) || [];
   if(nodes.length>0) value = Element.collectTextNodes(nodes[0], this.options.select);
  } else
   value = Element.collectTextNodesIgnoreClass(selectedElement, 'informal');
  
  var lastTokenPos = this.findLastToken();
  if (lastTokenPos != -1) {
   var newValue = this.element.value.substr(0, lastTokenPos + 1);
   var whitespace = this.element.value.substr(lastTokenPos + 1).match(/^\s+/);
   if (whitespace)
    newValue += whitespace[0];
   this.element.value = newValue + value;
  } else {
   this.element.value = value;
  }
  this.element.focus();
  
  if (this.options.afterUpdateElement)
   this.options.afterUpdateElement(this.element, selectedElement);
 },

 updateChoices: function(choices) {
  if(!this.changed && this.hasFocus) {
   this.update.innerHTML = choices;
   Element.cleanWhitespace(this.update);
   Element.cleanWhitespace(this.update.down());

   if(this.update.firstChild && this.update.down().childNodes) {
    this.entryCount = 
     this.update.down().childNodes.length;
    for (var i = 0; i < this.entryCount; i++) {
     var entry = this.getEntry(i);
     entry.autocompleteIndex = i;
     this.addObservers(entry);
    }
   } else { 
    this.entryCount = 0;
   }

   this.stopIndicator();
   this.index = 0;
   
   if(this.entryCount==1 && this.options.autoSelect) {
    this.selectEntry();
    this.hide();
   } else {
    this.render();
   }
  }
 },

 addObservers: function(element) {
  Event.observe(element, "mouseover", this.onHover.bindAsEventListener(this));
  Event.observe(element, "click", this.onClick.bindAsEventListener(this));
 },

 onObserverEvent: function() {
  this.changed = false;  
  if(this.getToken().length>=this.options.minChars) {
   this.getUpdatedChoices();
  } else {
   this.active = false;
   this.hide();
  }
 },

 getToken: function() {
  var tokenPos = this.findLastToken();
  if (tokenPos != -1)
   var ret = this.element.value.substr(tokenPos + 1).replace(/^\s+/,'').replace(/\s+$/,'');
  else
   var ret = this.element.value;

  return /\n/.test(ret) ? '' : ret;
 },

 findLastToken: function() {
  var lastTokenPos = -1;

  for (var i=0; i<this.options.tokens.length; i++) {
   var thisTokenPos = this.element.value.lastIndexOf(this.options.tokens[i]);
   if (thisTokenPos > lastTokenPos)
    lastTokenPos = thisTokenPos;
  }
  return lastTokenPos;
 }
}

Ajax.Autocompleter = Class.create();
Object.extend(Object.extend(Ajax.Autocompleter.prototype, Autocompleter.Base.prototype), {
 initialize: function(element, update, url, options) {
  this.baseInitialize(element, update, options);
  this.options.asynchronous = true;
  this.options.onComplete  = this.onComplete.bind(this);
  this.options.defaultParams = this.options.parameters || null;
  this.url          = url;
 },

 getUpdatedChoices: function() {
  this.startIndicator();
  
  var entry = encodeURIComponent(this.options.paramName) + '=' + 
   encodeURIComponent(this.getToken());

  this.options.parameters = this.options.callback ?
   this.options.callback(this.element, entry) : entry;

  if(this.options.defaultParams) 
   this.options.parameters += '&' + this.options.defaultParams;
  
  new Ajax.Request(this.url, this.options);
 },

 onComplete: function(request) {
  this.updateChoices(request.responseText);
 }

});



Autocompleter.Local = Class.create();
Autocompleter.Local.prototype = Object.extend(new Autocompleter.Base(), {
 initialize: function(element, update, array, options) {
  this.baseInitialize(element, update, options);
  this.options.array = array;
 },

 getUpdatedChoices: function() {
  this.updateChoices(this.options.selector(this));
 },

 setOptions: function(options) {
  this.options = Object.extend({
   choices: 10,
   partialSearch: true,
   partialChars: 2,
   ignoreCase: true,
   fullSearch: false,
   selector: function(instance) {
    var ret    = []; 
    var partial  = []; 
    var entry   = instance.getToken();
    var count   = 0;

    for (var i = 0; i < instance.options.array.length && 
     ret.length < instance.options.choices ; i++) { 

     var elem = instance.options.array[i];
     var foundPos = instance.options.ignoreCase ? 
      elem.toLowerCase().indexOf(entry.toLowerCase()) : 
      elem.indexOf(entry);

     while (foundPos != -1) {
      if (foundPos == 0 && elem.length != entry.length) { 
       ret.push("<li><strong>" + elem.substr(0, entry.length) + "</strong>" + 
        elem.substr(entry.length) + "</li>");
       break;
      } else if (entry.length >= instance.options.partialChars && 
       instance.options.partialSearch && foundPos != -1) {
       if (instance.options.fullSearch || /\s/.test(elem.substr(foundPos-1,1))) {
        partial.push("<li>" + elem.substr(0, foundPos) + "<strong>" +
         elem.substr(foundPos, entry.length) + "</strong>" + elem.substr(
         foundPos + entry.length) + "</li>");
        break;
       }
      }

      foundPos = instance.options.ignoreCase ? 
       elem.toLowerCase().indexOf(entry.toLowerCase(), foundPos + 1) : 
       elem.indexOf(entry, foundPos + 1);

     }
    }
    if (partial.length)
     ret = ret.concat(partial.slice(0, instance.options.choices - ret.length))
    return "<ul>" + ret.join('') + "</ul>";
   }
  }, options || {});
 }
});


Field.scrollFreeActivate = function(field) {
 setTimeout(function() {
  Field.activate(field);
 }, 1);
}

Ajax.InPlaceEditor = Class.create();
Ajax.InPlaceEditor.defaultHighlightColor = "#FFFF99";
Ajax.InPlaceEditor.prototype = {
 initialize: function(element, url, options) {
  this.url = url;
  this.element = $(element);

  this.options = Object.extend({
   paramName: "value",
   okButton: true,
   okLink: false,
   okText: "ok",
   cancelButton: false,
   cancelLink: true,
   cancelText: "cancel",
   textBeforeControls: '',
   textBetweenControls: '',
   textAfterControls: '',
   savingText: "Saving...",
   clickToEditText: "Click to edit",
   okText: "ok",
   rows: 1,
   onComplete: function(transport, element) {
    new Effect.Highlight(element, {startcolor: this.options.highlightcolor});
   },
   onFailure: function(transport) {
    alert("Error communicating with the server: " + transport.responseText.stripTags());
   },
   callback: function(form) {
    return Form.serialize(form);
   },
   handleLineBreaks: true,
   loadingText: 'Loading...',
   savingClassName: 'inplaceeditor-saving',
   loadingClassName: 'inplaceeditor-loading',
   formClassName: 'inplaceeditor-form',
   highlightcolor: Ajax.InPlaceEditor.defaultHighlightColor,
   highlightendcolor: "#FFFFFF",
   externalControl: null,
   submitOnBlur: false,
   ajaxOptions: {},
   evalScripts: false
  }, options || {});

  if(!this.options.formId && this.element.id) {
   this.options.formId = this.element.id + "-inplaceeditor";
   if ($(this.options.formId)) {
    
    this.options.formId = null;
   }
  }
  
  if (this.options.externalControl) {
   this.options.externalControl = $(this.options.externalControl);
  }
  
  this.originalBackground = Element.getStyle(this.element, 'background-color');
  if (!this.originalBackground) {
   this.originalBackground = "transparent";
  }
  
  this.element.title = this.options.clickToEditText;
  
  this.onclickListener = this.enterEditMode.bindAsEventListener(this);
  this.mouseoverListener = this.enterHover.bindAsEventListener(this);
  this.mouseoutListener = this.leaveHover.bindAsEventListener(this);
  Event.observe(this.element, 'click', this.onclickListener);
  Event.observe(this.element, 'mouseover', this.mouseoverListener);
  Event.observe(this.element, 'mouseout', this.mouseoutListener);
  if (this.options.externalControl) {
   Event.observe(this.options.externalControl, 'click', this.onclickListener);
   Event.observe(this.options.externalControl, 'mouseover', this.mouseoverListener);
   Event.observe(this.options.externalControl, 'mouseout', this.mouseoutListener);
  }
 },
 enterEditMode: function(evt) {
  if (this.saving) return;
  if (this.editing) return;
  this.editing = true;
  this.onEnterEditMode();
  if (this.options.externalControl) {
   Element.hide(this.options.externalControl);
  }
  Element.hide(this.element);
  this.createForm();
  this.element.parentNode.insertBefore(this.form, this.element);
  if (!this.options.loadTextURL) Field.scrollFreeActivate(this.editField);
  
  if (evt) {
   Event.stop(evt);
  }
  return false;
 },
 createForm: function() {
  this.form = document.createElement("form");
  this.form.id = this.options.formId;
  Element.addClassName(this.form, this.options.formClassName)
  this.form.onsubmit = this.onSubmit.bind(this);

  this.createEditField();

  if (this.options.textarea) {
   var br = document.createElement("br");
   this.form.appendChild(br);
  }
  
  if (this.options.textBeforeControls)
   this.form.appendChild(document.createTextNode(this.options.textBeforeControls));

  if (this.options.okButton) {
   var okButton = document.createElement("input");
   okButton.type = "submit";
   okButton.value = this.options.okText;
   okButton.className = 'editor_ok_button';
   this.form.appendChild(okButton);
  }
  
  if (this.options.okLink) {
   var okLink = document.createElement("a");
   okLink.href = "#";
   okLink.appendChild(document.createTextNode(this.options.okText));
   okLink.onclick = this.onSubmit.bind(this);
   okLink.className = 'editor_ok_link';
   this.form.appendChild(okLink);
  }
  
  if (this.options.textBetweenControls && 
   (this.options.okLink || this.options.okButton) && 
   (this.options.cancelLink || this.options.cancelButton))
   this.form.appendChild(document.createTextNode(this.options.textBetweenControls));
   
  if (this.options.cancelButton) {
   var cancelButton = document.createElement("input");
   cancelButton.type = "submit";
   cancelButton.value = this.options.cancelText;
   cancelButton.onclick = this.onclickCancel.bind(this);
   cancelButton.className = 'editor_cancel_button';
   this.form.appendChild(cancelButton);
  }

  if (this.options.cancelLink) {
   var cancelLink = document.createElement("a");
   cancelLink.href = "#";
   cancelLink.appendChild(document.createTextNode(this.options.cancelText));
   cancelLink.onclick = this.onclickCancel.bind(this);
   cancelLink.className = 'editor_cancel editor_cancel_link';   
   this.form.appendChild(cancelLink);
  }
  
  if (this.options.textAfterControls)
   this.form.appendChild(document.createTextNode(this.options.textAfterControls));
 },
 hasHTMLLineBreaks: function(string) {
  if (!this.options.handleLineBreaks) return false;
  return string.match(/<br/i) || string.match(/<p>/i);
 },
 convertHTMLLineBreaks: function(string) {
  return string.replace(/<br>/gi, "\n").replace(/<br\/>/gi, "\n").replace(/<\/p>/gi, "\n").replace(/<p>/gi, "");
 },
 createEditField: function() {
  var text;
  if(this.options.loadTextURL) {
   text = this.options.loadingText;
  } else {
   text = this.getText();
  }

  var obj = this;
  
  if (this.options.rows == 1 && !this.hasHTMLLineBreaks(text)) {
   this.options.textarea = false;
   var textField = document.createElement("input");
   textField.obj = this;
   textField.type = "text";
   textField.name = this.options.paramName;
   textField.value = text;
   textField.style.backgroundColor = this.options.highlightcolor;
   textField.className = 'editor_field';
   var size = this.options.size || this.options.cols || 0;
   if (size != 0) textField.size = size;
   if (this.options.submitOnBlur)
    textField.onblur = this.onSubmit.bind(this);
   this.editField = textField;
  } else {
   this.options.textarea = true;
   var textArea = document.createElement("textarea");
   textArea.obj = this;
   textArea.name = this.options.paramName;
   textArea.value = this.convertHTMLLineBreaks(text);
   textArea.rows = this.options.rows;
   textArea.cols = this.options.cols || 40;
   textArea.className = 'editor_field';   
   if (this.options.submitOnBlur)
    textArea.onblur = this.onSubmit.bind(this);
   this.editField = textArea;
  }
  
  if(this.options.loadTextURL) {
   this.loadExternalText();
  }
  this.form.appendChild(this.editField);
 },
 getText: function() {
  return this.element.innerHTML;
 },
 loadExternalText: function() {
  Element.addClassName(this.form, this.options.loadingClassName);
  this.editField.disabled = true;
  new Ajax.Request(
   this.options.loadTextURL,
   Object.extend({
    asynchronous: true,
    onComplete: this.onLoadedExternalText.bind(this)
   }, this.options.ajaxOptions)
  );
 },
 onLoadedExternalText: function(transport) {
  Element.removeClassName(this.form, this.options.loadingClassName);
  this.editField.disabled = false;
  this.editField.value = transport.responseText.stripTags();
  Field.scrollFreeActivate(this.editField);
 },
 onclickCancel: function() {
  this.onComplete();
  this.leaveEditMode();
  return false;
 },
 onFailure: function(transport) {
  this.options.onFailure(transport);
  if (this.oldInnerHTML) {
   this.element.innerHTML = this.oldInnerHTML;
   this.oldInnerHTML = null;
  }
  return false;
 },
 onSubmit: function() {
  
  var form = this.form;
  var value = this.editField.value;
  
  
  this.onLoading();
  
  if (this.options.evalScripts) {
   new Ajax.Request(
    this.url, Object.extend({
     parameters: this.options.callback(form, value),
     onComplete: this.onComplete.bind(this),
     onFailure: this.onFailure.bind(this),
     asynchronous:true, 
     evalScripts:true
    }, this.options.ajaxOptions));
  } else {
   new Ajax.Updater(
    { success: this.element,
     
     failure: null }, 
    this.url, Object.extend({
     parameters: this.options.callback(form, value),
     onComplete: this.onComplete.bind(this),
     onFailure: this.onFailure.bind(this)
    }, this.options.ajaxOptions));
  }
  
  if (arguments.length > 1) {
   Event.stop(arguments[0]);
  }
  return false;
 },
 onLoading: function() {
  this.saving = true;
  this.removeForm();
  this.leaveHover();
  this.showSaving();
 },
 showSaving: function() {
  this.oldInnerHTML = this.element.innerHTML;
  this.element.innerHTML = this.options.savingText;
  Element.addClassName(this.element, this.options.savingClassName);
  this.element.style.backgroundColor = this.originalBackground;
  Element.show(this.element);
 },
 removeForm: function() {
  if(this.form) {
   if (this.form.parentNode) Element.remove(this.form);
   this.form = null;
  }
 },
 enterHover: function() {
  if (this.saving) return;
  this.element.style.backgroundColor = this.options.highlightcolor;
  if (this.effect) {
   this.effect.cancel();
  }
  Element.addClassName(this.element, this.options.hoverClassName)
 },
 leaveHover: function() {
  if (this.options.backgroundColor) {
   this.element.style.backgroundColor = this.oldBackground;
  }
  Element.removeClassName(this.element, this.options.hoverClassName)
  if (this.saving) return;
  this.effect = new Effect.Highlight(this.element, {
   startcolor: this.options.highlightcolor,
   endcolor: this.options.highlightendcolor,
   restorecolor: this.originalBackground
  });
 },
 leaveEditMode: function() {
  Element.removeClassName(this.element, this.options.savingClassName);
  this.removeForm();
  this.leaveHover();
  this.element.style.backgroundColor = this.originalBackground;
  Element.show(this.element);
  if (this.options.externalControl) {
   Element.show(this.options.externalControl);
  }
  this.editing = false;
  this.saving = false;
  this.oldInnerHTML = null;
  this.onLeaveEditMode();
 },
 onComplete: function(transport) {
  this.leaveEditMode();
  this.options.onComplete.bind(this)(transport, this.element);
 },
 onEnterEditMode: function() {},
 onLeaveEditMode: function() {},
 dispose: function() {
  if (this.oldInnerHTML) {
   this.element.innerHTML = this.oldInnerHTML;
  }
  this.leaveEditMode();
  Event.stopObserving(this.element, 'click', this.onclickListener);
  Event.stopObserving(this.element, 'mouseover', this.mouseoverListener);
  Event.stopObserving(this.element, 'mouseout', this.mouseoutListener);
  if (this.options.externalControl) {
   Event.stopObserving(this.options.externalControl, 'click', this.onclickListener);
   Event.stopObserving(this.options.externalControl, 'mouseover', this.mouseoverListener);
   Event.stopObserving(this.options.externalControl, 'mouseout', this.mouseoutListener);
  }
 }
};

Ajax.InPlaceCollectionEditor = Class.create();
Object.extend(Ajax.InPlaceCollectionEditor.prototype, Ajax.InPlaceEditor.prototype);
Object.extend(Ajax.InPlaceCollectionEditor.prototype, {
 createEditField: function() {
  if (!this.cached_selectTag) {
   var selectTag = document.createElement("select");
   var collection = this.options.collection || [];
   var optionTag;
   collection.each(function(e,i) {
    optionTag = document.createElement("option");
    optionTag.value = (e instanceof Array) ? e[0] : e;
    if((typeof this.options.value == 'undefined') && 
     ((e instanceof Array) ? this.element.innerHTML == e[1] : e == optionTag.value)) optionTag.selected = true;
    if(this.options.value==optionTag.value) optionTag.selected = true;
    optionTag.appendChild(document.createTextNode((e instanceof Array) ? e[1] : e));
    selectTag.appendChild(optionTag);
   }.bind(this));
   this.cached_selectTag = selectTag;
  }

  this.editField = this.cached_selectTag;
  if(this.options.loadTextURL) this.loadExternalText();
  this.form.appendChild(this.editField);
  this.options.callback = function(form, value) {
   return "value=" + encodeURIComponent(value);
  }
 }
});



Form.Element.DelayedObserver = Class.create();
Form.Element.DelayedObserver.prototype = {
 initialize: function(element, delay, callback) {
  this.delay   = delay || 0.5;
  this.element  = $(element);
  this.callback = callback;
  this.timer   = null;
  this.lastValue = $F(this.element); 
  Event.observe(this.element,'keyup',this.delayedListener.bindAsEventListener(this));
 },
 delayedListener: function(event) {
  if(this.lastValue == $F(this.element)) return;
  if(this.timer) clearTimeout(this.timer);
  this.timer = setTimeout(this.onTimerEvent.bind(this), this.delay * 1000);
  this.lastValue = $F(this.element);
 },
 onTimerEvent: function() {
  this.timer = null;
  this.callback(this.element, $F(this.element));
 }
};
/*
 * jQuery JavaScript Library v1.3.1
 */
(function(){var l=this,g,y=l.jQuery,p=l.$,o=l.jQuery=l.$=function(E,F){return new o.fn.init(E,F)},D=/^[^<]*(<(.|\s)+>)[^>]*$|^#([\w-]+)$/,f=/^.[^:#\[\.,]*$/;o.fn=o.prototype={init:function(E,H){E=E||document;if(E.nodeType){this[0]=E;this.length=1;this.context=E;return this}if(typeof E==="string"){var G=D.exec(E);if(G&&(G[1]||!H)){if(G[1]){E=o.clean([G[1]],H)}else{var I=document.getElementById(G[3]);if(I&&I.id!=G[3]){return o().find(E)}var F=o(I||[]);F.context=document;F.selector=E;return F}}else{return o(H).find(E)}}else{if(o.isFunction(E)){return o(document).ready(E)}}if(E.selector&&E.context){this.selector=E.selector;this.context=E.context}return this.setArray(o.makeArray(E))},selector:"",jquery:"1.3.1",size:function(){return this.length},get:function(E){return E===g?o.makeArray(this):this[E]},pushStack:function(F,H,E){var G=o(F);G.prevObject=this;G.context=this.context;if(H==="find"){G.selector=this.selector+(this.selector?" ":"")+E}else{if(H){G.selector=this.selector+"."+H+"("+E+")"}}return G},setArray:function(E){this.length=0;Array.prototype.push.apply(this,E);return this},each:function(F,E){return o.each(this,F,E)},index:function(E){return o.inArray(E&&E.jquery?E[0]:E,this)},attr:function(F,H,G){var E=F;if(typeof F==="string"){if(H===g){return this[0]&&o[G||"attr"](this[0],F)}else{E={};E[F]=H}}return this.each(function(I){for(F in E){o.attr(G?this.style:this,F,o.prop(this,E[F],G,I,F))}})},css:function(E,F){if((E=="width"||E=="height")&&parseFloat(F)<0){F=g}return this.attr(E,F,"curCSS")},text:function(F){if(typeof F!=="object"&&F!=null){return this.empty().append((this[0]&&this[0].ownerDocument||document).createTextNode(F))}var E="";o.each(F||this,function(){o.each(this.childNodes,function(){if(this.nodeType!=8){E+=this.nodeType!=1?this.nodeValue:o.fn.text([this])}})});return E},wrapAll:function(E){if(this[0]){var F=o(E,this[0].ownerDocument).clone();if(this[0].parentNode){F.insertBefore(this[0])}F.map(function(){var G=this;while(G.firstChild){G=G.firstChild}return G}).append(this)}return this},wrapInner:function(E){return this.each(function(){o(this).contents().wrapAll(E)})},wrap:function(E){return this.each(function(){o(this).wrapAll(E)})},append:function(){return this.domManip(arguments,true,function(E){if(this.nodeType==1){this.appendChild(E)}})},prepend:function(){return this.domManip(arguments,true,function(E){if(this.nodeType==1){this.insertBefore(E,this.firstChild)}})},before:function(){return this.domManip(arguments,false,function(E){this.parentNode.insertBefore(E,this)})},after:function(){return this.domManip(arguments,false,function(E){this.parentNode.insertBefore(E,this.nextSibling)})},end:function(){return this.prevObject||o([])},push:[].push,find:function(E){if(this.length===1&&!/,/.test(E)){var G=this.pushStack([],"find",E);G.length=0;o.find(E,this[0],G);return G}else{var F=o.map(this,function(H){return o.find(E,H)});return this.pushStack(/[^+>] [^+>]/.test(E)?o.unique(F):F,"find",E)}},clone:function(F){var E=this.map(function(){if(!o.support.noCloneEvent&&!o.isXMLDoc(this)){var I=this.cloneNode(true),H=document.createElement("div");H.appendChild(I);return o.clean([H.innerHTML])[0]}else{return this.cloneNode(true)}});var G=E.find("*").andSelf().each(function(){if(this[h]!==g){this[h]=null}});if(F===true){this.find("*").andSelf().each(function(I){if(this.nodeType==3){return}var H=o.data(this,"events");for(var K in H){for(var J in H[K]){o.event.add(G[I],K,H[K][J],H[K][J].data)}}})}return E},filter:function(E){return this.pushStack(o.isFunction(E)&&o.grep(this,function(G,F){return E.call(G,F)})||o.multiFilter(E,o.grep(this,function(F){return F.nodeType===1})),"filter",E)},closest:function(E){var F=o.expr.match.POS.test(E)?o(E):null;return this.map(function(){var G=this;while(G&&G.ownerDocument){if(F?F.index(G)>-1:o(G).is(E)){return G}G=G.parentNode}})},not:function(E){if(typeof E==="string"){if(f.test(E)){return this.pushStack(o.multiFilter(E,this,true),"not",E)}else{E=o.multiFilter(E,this)}}var F=E.length&&E[E.length-1]!==g&&!E.nodeType;return this.filter(function(){return F?o.inArray(this,E)<0:this!=E})},add:function(E){return this.pushStack(o.unique(o.merge(this.get(),typeof E==="string"?o(E):o.makeArray(E))))},is:function(E){return !!E&&o.multiFilter(E,this).length>0},hasClass:function(E){return !!E&&this.is("."+E)},val:function(K){if(K===g){var E=this[0];if(E){if(o.nodeName(E,"option")){return(E.attributes.value||{}).specified?E.value:E.text}if(o.nodeName(E,"select")){var I=E.selectedIndex,L=[],M=E.options,H=E.type=="select-one";if(I<0){return null}for(var F=H?I:0,J=H?I+1:M.length;F<J;F++){var G=M[F];if(G.selected){K=o(G).val();if(H){return K}L.push(K)}}return L}return(E.value||"").replace(/\r/g,"")}return g}if(typeof K==="number"){K+=""}return this.each(function(){if(this.nodeType!=1){return}if(o.isArray(K)&&/radio|checkbox/.test(this.type)){this.checked=(o.inArray(this.value,K)>=0||o.inArray(this.name,K)>=0)}else{if(o.nodeName(this,"select")){var N=o.makeArray(K);o("option",this).each(function(){this.selected=(o.inArray(this.value,N)>=0||o.inArray(this.text,N)>=0)});if(!N.length){this.selectedIndex=-1}}else{this.value=K}}})},html:function(E){return E===g?(this[0]?this[0].innerHTML:null):this.empty().append(E)},replaceWith:function(E){return this.after(E).remove()},eq:function(E){return this.slice(E,+E+1)},slice:function(){return this.pushStack(Array.prototype.slice.apply(this,arguments),"slice",Array.prototype.slice.call(arguments).join(","))},map:function(E){return this.pushStack(o.map(this,function(G,F){return E.call(G,F,G)}))},andSelf:function(){return this.add(this.prevObject)},domManip:function(K,N,M){if(this[0]){var J=(this[0].ownerDocument||this[0]).createDocumentFragment(),G=o.clean(K,(this[0].ownerDocument||this[0]),J),I=J.firstChild,E=this.length>1?J.cloneNode(true):J;if(I){for(var H=0,F=this.length;H<F;H++){M.call(L(this[H],I),H>0?E.cloneNode(true):J)}}if(G){o.each(G,z)}}return this;function L(O,P){return N&&o.nodeName(O,"table")&&o.nodeName(P,"tr")?(O.getElementsByTagName("tbody")[0]||O.appendChild(O.ownerDocument.createElement("tbody"))):O}}};o.fn.init.prototype=o.fn;function z(E,F){if(F.src){o.ajax({url:F.src,async:false,dataType:"script"})}else{o.globalEval(F.text||F.textContent||F.innerHTML||"")}if(F.parentNode){F.parentNode.removeChild(F)}}function e(){return +new Date}o.extend=o.fn.extend=function(){var J=arguments[0]||{},H=1,I=arguments.length,E=false,G;if(typeof J==="boolean"){E=J;J=arguments[1]||{};H=2}if(typeof J!=="object"&&!o.isFunction(J)){J={}}if(I==H){J=this;--H}for(;H<I;H++){if((G=arguments[H])!=null){for(var F in G){var K=J[F],L=G[F];if(J===L){continue}if(E&&L&&typeof L==="object"&&!L.nodeType){J[F]=o.extend(E,K||(L.length!=null?[]:{}),L)}else{if(L!==g){J[F]=L}}}}}return J};var b=/z-?index|font-?weight|opacity|zoom|line-?height/i,q=document.defaultView||{},s=Object.prototype.toString;o.extend({noConflict:function(E){l.$=p;if(E){l.jQuery=y}return o},isFunction:function(E){return s.call(E)==="[object Function]"},isArray:function(E){return s.call(E)==="[object Array]"},isXMLDoc:function(E){return E.nodeType===9&&E.documentElement.nodeName!=="HTML"||!!E.ownerDocument&&o.isXMLDoc(E.ownerDocument)},globalEval:function(G){G=o.trim(G);if(G){var F=document.getElementsByTagName("head")[0]||document.documentElement,E=document.createElement("script");E.type="text/javascript";if(o.support.scriptEval){E.appendChild(document.createTextNode(G))}else{E.text=G}F.insertBefore(E,F.firstChild);F.removeChild(E)}},nodeName:function(F,E){return F.nodeName&&F.nodeName.toUpperCase()==E.toUpperCase()},each:function(G,K,F){var E,H=0,I=G.length;if(F){if(I===g){for(E in G){if(K.apply(G[E],F)===false){break}}}else{for(;H<I;){if(K.apply(G[H++],F)===false){break}}}}else{if(I===g){for(E in G){if(K.call(G[E],E,G[E])===false){break}}}else{for(var J=G[0];H<I&&K.call(J,H,J)!==false;J=G[++H]){}}}return G},prop:function(H,I,G,F,E){if(o.isFunction(I)){I=I.call(H,F)}return typeof I==="number"&&G=="curCSS"&&!b.test(E)?I+"px":I},className:{add:function(E,F){o.each((F||"").split(/\s+/),function(G,H){if(E.nodeType==1&&!o.className.has(E.className,H)){E.className+=(E.className?" ":"")+H}})},remove:function(E,F){if(E.nodeType==1){E.className=F!==g?o.grep(E.className.split(/\s+/),function(G){return !o.className.has(F,G)}).join(" "):""}},has:function(F,E){return F&&o.inArray(E,(F.className||F).toString().split(/\s+/))>-1}},swap:function(H,G,I){var E={};for(var F in G){E[F]=H.style[F];H.style[F]=G[F]}I.call(H);for(var F in G){H.style[F]=E[F]}},css:function(G,E,I){if(E=="width"||E=="height"){var K,F={position:"absolute",visibility:"hidden",display:"block"},J=E=="width"?["Left","Right"]:["Top","Bottom"];function H(){K=E=="width"?G.offsetWidth:G.offsetHeight;var M=0,L=0;o.each(J,function(){M+=parseFloat(o.curCSS(G,"padding"+this,true))||0;L+=parseFloat(o.curCSS(G,"border"+this+"Width",true))||0});K-=Math.round(M+L)}if(o(G).is(":visible")){H()}else{o.swap(G,F,H)}return Math.max(0,K)}return o.curCSS(G,E,I)},curCSS:function(I,F,G){var L,E=I.style;if(F=="opacity"&&!o.support.opacity){L=o.attr(E,"opacity");return L==""?"1":L}if(F.match(/float/i)){F=w}if(!G&&E&&E[F]){L=E[F]}else{if(q.getComputedStyle){if(F.match(/float/i)){F="float"}F=F.replace(/([A-Z])/g,"-$1").toLowerCase();var M=q.getComputedStyle(I,null);if(M){L=M.getPropertyValue(F)}if(F=="opacity"&&L==""){L="1"}}else{if(I.currentStyle){var J=F.replace(/\-(\w)/g,function(N,O){return O.toUpperCase()});L=I.currentStyle[F]||I.currentStyle[J];if(!/^\d+(px)?$/i.test(L)&&/^\d/.test(L)){var H=E.left,K=I.runtimeStyle.left;I.runtimeStyle.left=I.currentStyle.left;E.left=L||0;L=E.pixelLeft+"px";E.left=H;I.runtimeStyle.left=K}}}}return L},clean:function(F,K,I){K=K||document;if(typeof K.createElement==="undefined"){K=K.ownerDocument||K[0]&&K[0].ownerDocument||document}if(!I&&F.length===1&&typeof F[0]==="string"){var H=/^<(\w+)\s*\/?>$/.exec(F[0]);if(H){return[K.createElement(H[1])]}}var G=[],E=[],L=K.createElement("div");o.each(F,function(P,R){if(typeof R==="number"){R+=""}if(!R){return}if(typeof R==="string"){R=R.replace(/(<(\w+)[^>]*?)\/>/g,function(T,U,S){return S.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i)?T:U+"></"+S+">"});var O=o.trim(R).toLowerCase();var Q=!O.indexOf("<opt")&&[1,"<select multiple='multiple'>","</select>"]||!O.indexOf("<leg")&&[1,"<fieldset>","</fieldset>"]||O.match(/^<(thead|tbody|tfoot|colg|cap)/)&&[1,"<table>","</table>"]||!O.indexOf("<tr")&&[2,"<table><tbody>","</tbody></table>"]||(!O.indexOf("<td")||!O.indexOf("<th"))&&[3,"<table><tbody><tr>","</tr></tbody></table>"]||!O.indexOf("<col")&&[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"]||!o.support.htmlSerialize&&[1,"div<div>","</div>"]||[0,"",""];L.innerHTML=Q[1]+R+Q[2];while(Q[0]--){L=L.lastChild}if(!o.support.tbody){var N=!O.indexOf("<table")&&O.indexOf("<tbody")<0?L.firstChild&&L.firstChild.childNodes:Q[1]=="<table>"&&O.indexOf("<tbody")<0?L.childNodes:[];for(var M=N.length-1;M>=0;--M){if(o.nodeName(N[M],"tbody")&&!N[M].childNodes.length){N[M].parentNode.removeChild(N[M])}}}if(!o.support.leadingWhitespace&&/^\s/.test(R)){L.insertBefore(K.createTextNode(R.match(/^\s*/)[0]),L.firstChild)}R=o.makeArray(L.childNodes)}if(R.nodeType){G.push(R)}else{G=o.merge(G,R)}});if(I){for(var J=0;G[J];J++){if(o.nodeName(G[J],"script")&&(!G[J].type||G[J].type.toLowerCase()==="text/javascript")){E.push(G[J].parentNode?G[J].parentNode.removeChild(G[J]):G[J])}else{if(G[J].nodeType===1){G.splice.apply(G,[J+1,0].concat(o.makeArray(G[J].getElementsByTagName("script"))))}I.appendChild(G[J])}}return E}return G},attr:function(J,G,K){if(!J||J.nodeType==3||J.nodeType==8){return g}var H=!o.isXMLDoc(J),L=K!==g;G=H&&o.props[G]||G;if(J.tagName){var F=/href|src|style/.test(G);if(G=="selected"&&J.parentNode){J.parentNode.selectedIndex}if(G in J&&H&&!F){if(L){if(G=="type"&&o.nodeName(J,"input")&&J.parentNode){throw"type property can't be changed"}J[G]=K}if(o.nodeName(J,"form")&&J.getAttributeNode(G)){return J.getAttributeNode(G).nodeValue}if(G=="tabIndex"){var I=J.getAttributeNode("tabIndex");return I&&I.specified?I.value:J.nodeName.match(/(button|input|object|select|textarea)/i)?0:J.nodeName.match(/^(a|area)$/i)&&J.href?0:g}return J[G]}if(!o.support.style&&H&&G=="style"){return o.attr(J.style,"cssText",K)}if(L){J.setAttribute(G,""+K)}var E=!o.support.hrefNormalized&&H&&F?J.getAttribute(G,2):J.getAttribute(G);return E===null?g:E}if(!o.support.opacity&&G=="opacity"){if(L){J.zoom=1;J.filter=(J.filter||"").replace(/alpha\([^)]*\)/,"")+(parseInt(K)+""=="NaN"?"":"alpha(opacity="+K*100+")")}return J.filter&&J.filter.indexOf("opacity=")>=0?(parseFloat(J.filter.match(/opacity=([^)]*)/)[1])/100)+"":""}G=G.replace(/-([a-z])/ig,function(M,N){return N.toUpperCase()});if(L){J[G]=K}return J[G]},trim:function(E){return(E||"").replace(/^\s+|\s+$/g,"")},makeArray:function(G){var E=[];if(G!=null){var F=G.length;if(F==null||typeof G==="string"||o.isFunction(G)||G.setInterval){E[0]=G}else{while(F){E[--F]=G[F]}}}return E},inArray:function(G,H){for(var E=0,F=H.length;E<F;E++){if(H[E]===G){return E}}return -1},merge:function(H,E){var F=0,G,I=H.length;if(!o.support.getAll){while((G=E[F++])!=null){if(G.nodeType!=8){H[I++]=G}}}else{while((G=E[F++])!=null){H[I++]=G}}return H},unique:function(K){var F=[],E={};try{for(var G=0,H=K.length;G<H;G++){var J=o.data(K[G]);if(!E[J]){E[J]=true;F.push(K[G])}}}catch(I){F=K}return F},grep:function(F,J,E){var G=[];for(var H=0,I=F.length;H<I;H++){if(!E!=!J(F[H],H)){G.push(F[H])}}return G},map:function(E,J){var F=[];for(var G=0,H=E.length;G<H;G++){var I=J(E[G],G);if(I!=null){F[F.length]=I}}return F.concat.apply([],F)}});var C=navigator.userAgent.toLowerCase();o.browser={version:(C.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/)||[0,"0"])[1],safari:/webkit/.test(C),opera:/opera/.test(C),msie:/msie/.test(C)&&!/opera/.test(C),mozilla:/mozilla/.test(C)&&!/(compatible|webkit)/.test(C)};o.each({parent:function(E){return E.parentNode},parents:function(E){return o.dir(E,"parentNode")},next:function(E){return o.nth(E,2,"nextSibling")},prev:function(E){return o.nth(E,2,"previousSibling")},nextAll:function(E){return o.dir(E,"nextSibling")},prevAll:function(E){return o.dir(E,"previousSibling")},siblings:function(E){return o.sibling(E.parentNode.firstChild,E)},children:function(E){return o.sibling(E.firstChild)},contents:function(E){return o.nodeName(E,"iframe")?E.contentDocument||E.contentWindow.document:o.makeArray(E.childNodes)}},function(E,F){o.fn[E]=function(G){var H=o.map(this,F);if(G&&typeof G=="string"){H=o.multiFilter(G,H)}return this.pushStack(o.unique(H),E,G)}});o.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(E,F){o.fn[E]=function(){var G=arguments;return this.each(function(){for(var H=0,I=G.length;H<I;H++){o(G[H])[F](this)}})}});o.each({removeAttr:function(E){o.attr(this,E,"");if(this.nodeType==1){this.removeAttribute(E)}},addClass:function(E){o.className.add(this,E)},removeClass:function(E){o.className.remove(this,E)},toggleClass:function(F,E){if(typeof E!=="boolean"){E=!o.className.has(this,F)}o.className[E?"add":"remove"](this,F)},remove:function(E){if(!E||o.filter(E,[this]).length){o("*",this).add([this]).each(function(){o.event.remove(this);o.removeData(this)});if(this.parentNode){this.parentNode.removeChild(this)}}},empty:function(){o(">*",this).remove();while(this.firstChild){this.removeChild(this.firstChild)}}},function(E,F){o.fn[E]=function(){return this.each(F,arguments)}});function j(E,F){return E[0]&&parseInt(o.curCSS(E[0],F,true),10)||0}var h="jQuery"+e(),v=0,A={};o.extend({cache:{},data:function(F,E,G){F=F==l?A:F;var H=F[h];if(!H){H=F[h]=++v}if(E&&!o.cache[H]){o.cache[H]={}}if(G!==g){o.cache[H][E]=G}return E?o.cache[H][E]:H},removeData:function(F,E){F=F==l?A:F;var H=F[h];if(E){if(o.cache[H]){delete o.cache[H][E];E="";for(E in o.cache[H]){break}if(!E){o.removeData(F)}}}else{try{delete F[h]}catch(G){if(F.removeAttribute){F.removeAttribute(h)}}delete o.cache[H]}},queue:function(F,E,H){if(F){E=(E||"fx")+"queue";var G=o.data(F,E);if(!G||o.isArray(H)){G=o.data(F,E,o.makeArray(H))}else{if(H){G.push(H)}}}return G},dequeue:function(H,G){var E=o.queue(H,G),F=E.shift();if(!G||G==="fx"){F=E[0]}if(F!==g){F.call(H)}}});o.fn.extend({data:function(E,G){var H=E.split(".");H[1]=H[1]?"."+H[1]:"";if(G===g){var F=this.triggerHandler("getData"+H[1]+"!",[H[0]]);if(F===g&&this.length){F=o.data(this[0],E)}return F===g&&H[1]?this.data(H[0]):F}else{return this.trigger("setData"+H[1]+"!",[H[0],G]).each(function(){o.data(this,E,G)})}},removeData:function(E){return this.each(function(){o.removeData(this,E)})},queue:function(E,F){if(typeof E!=="string"){F=E;E="fx"}if(F===g){return o.queue(this[0],E)}return this.each(function(){var G=o.queue(this,E,F);if(E=="fx"&&G.length==1){G[0].call(this)}})},dequeue:function(E){return this.each(function(){o.dequeue(this,E)})}});
/*
 * Sizzle CSS Selector Engine - v0.9.3
 */
(function(){var Q=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]+['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[]+)+|[>+~])(\s*,\s*)?/g,K=0,G=Object.prototype.toString;var F=function(X,T,aa,ab){aa=aa||[];T=T||document;if(T.nodeType!==1&&T.nodeType!==9){return[]}if(!X||typeof X!=="string"){return aa}var Y=[],V,ae,ah,S,ac,U,W=true;Q.lastIndex=0;while((V=Q.exec(X))!==null){Y.push(V[1]);if(V[2]){U=RegExp.rightContext;break}}if(Y.length>1&&L.exec(X)){if(Y.length===2&&H.relative[Y[0]]){ae=I(Y[0]+Y[1],T)}else{ae=H.relative[Y[0]]?[T]:F(Y.shift(),T);while(Y.length){X=Y.shift();if(H.relative[X]){X+=Y.shift()}ae=I(X,ae)}}}else{var ad=ab?{expr:Y.pop(),set:E(ab)}:F.find(Y.pop(),Y.length===1&&T.parentNode?T.parentNode:T,P(T));ae=F.filter(ad.expr,ad.set);if(Y.length>0){ah=E(ae)}else{W=false}while(Y.length){var ag=Y.pop(),af=ag;if(!H.relative[ag]){ag=""}else{af=Y.pop()}if(af==null){af=T}H.relative[ag](ah,af,P(T))}}if(!ah){ah=ae}if(!ah){throw"Syntax error, unrecognized expression: "+(ag||X)}if(G.call(ah)==="[object Array]"){if(!W){aa.push.apply(aa,ah)}else{if(T.nodeType===1){for(var Z=0;ah[Z]!=null;Z++){if(ah[Z]&&(ah[Z]===true||ah[Z].nodeType===1&&J(T,ah[Z]))){aa.push(ae[Z])}}}else{for(var Z=0;ah[Z]!=null;Z++){if(ah[Z]&&ah[Z].nodeType===1){aa.push(ae[Z])}}}}}else{E(ah,aa)}if(U){F(U,T,aa,ab)}return aa};F.matches=function(S,T){return F(S,null,null,T)};F.find=function(Z,S,aa){var Y,W;if(!Z){return[]}for(var V=0,U=H.order.length;V<U;V++){var X=H.order[V],W;if((W=H.match[X].exec(Z))){var T=RegExp.leftContext;if(T.substr(T.length-1)!=="\\"){W[1]=(W[1]||"").replace(/\\/g,"");Y=H.find[X](W,S,aa);if(Y!=null){Z=Z.replace(H.match[X],"");break}}}}if(!Y){Y=S.getElementsByTagName("*")}return{set:Y,expr:Z}};F.filter=function(ab,aa,ae,V){var U=ab,ag=[],Y=aa,X,S;while(ab&&aa.length){for(var Z in H.filter){if((X=H.match[Z].exec(ab))!=null){var T=H.filter[Z],af,ad;S=false;if(Y==ag){ag=[]}if(H.preFilter[Z]){X=H.preFilter[Z](X,Y,ae,ag,V);if(!X){S=af=true}else{if(X===true){continue}}}if(X){for(var W=0;(ad=Y[W])!=null;W++){if(ad){af=T(ad,X,W,Y);var ac=V^!!af;if(ae&&af!=null){if(ac){S=true}else{Y[W]=false}}else{if(ac){ag.push(ad);S=true}}}}}if(af!==g){if(!ae){Y=ag}ab=ab.replace(H.match[Z],"");if(!S){return[]}break}}}ab=ab.replace(/\s*,\s*/,"");if(ab==U){if(S==null){throw"Syntax error, unrecognized expression: "+ab}else{break}}U=ab}return Y};var H=F.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF_-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF_-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF_-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF_-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*_-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF_-]|\\.)+)(?:\((['"]*)((?:\([^\)]+\)|[^\2\(\)]*)+)\2\))?/},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(S){return S.getAttribute("href")}},relative:{"+":function(W,T){for(var U=0,S=W.length;U<S;U++){var V=W[U];if(V){var X=V.previousSibling;while(X&&X.nodeType!==1){X=X.previousSibling}W[U]=typeof T==="string"?X||false:X===T}}if(typeof T==="string"){F.filter(T,W,true)}},">":function(X,T,Y){if(typeof T==="string"&&!/\W/.test(T)){T=Y?T:T.toUpperCase();for(var U=0,S=X.length;U<S;U++){var W=X[U];if(W){var V=W.parentNode;X[U]=V.nodeName===T?V:false}}}else{for(var U=0,S=X.length;U<S;U++){var W=X[U];if(W){X[U]=typeof T==="string"?W.parentNode:W.parentNode===T}}if(typeof T==="string"){F.filter(T,X,true)}}},"":function(V,T,X){var U="done"+(K++),S=R;if(!T.match(/\W/)){var W=T=X?T:T.toUpperCase();S=O}S("parentNode",T,U,V,W,X)},"~":function(V,T,X){var U="done"+(K++),S=R;if(typeof T==="string"&&!T.match(/\W/)){var W=T=X?T:T.toUpperCase();S=O}S("previousSibling",T,U,V,W,X)}},find:{ID:function(T,U,V){if(typeof U.getElementById!=="undefined"&&!V){var S=U.getElementById(T[1]);return S?[S]:[]}},NAME:function(S,T,U){if(typeof T.getElementsByName!=="undefined"&&!U){return T.getElementsByName(S[1])}},TAG:function(S,T){return T.getElementsByTagName(S[1])}},preFilter:{CLASS:function(V,T,U,S,Y){V=" "+V[1].replace(/\\/g,"")+" ";var X;for(var W=0;(X=T[W])!=null;W++){if(X){if(Y^(" "+X.className+" ").indexOf(V)>=0){if(!U){S.push(X)}}else{if(U){T[W]=false}}}}return false},ID:function(S){return S[1].replace(/\\/g,"")},TAG:function(T,S){for(var U=0;S[U]===false;U++){}return S[U]&&P(S[U])?T[1]:T[1].toUpperCase()},CHILD:function(S){if(S[1]=="nth"){var T=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(S[2]=="even"&&"2n"||S[2]=="odd"&&"2n+1"||!/\D/.test(S[2])&&"0n+"+S[2]||S[2]);S[2]=(T[1]+(T[2]||1))-0;S[3]=T[3]-0}S[0]="done"+(K++);return S},ATTR:function(T){var S=T[1].replace(/\\/g,"");if(H.attrMap[S]){T[1]=H.attrMap[S]}if(T[2]==="~="){T[4]=" "+T[4]+" "}return T},PSEUDO:function(W,T,U,S,X){if(W[1]==="not"){if(W[3].match(Q).length>1){W[3]=F(W[3],null,null,T)}else{var V=F.filter(W[3],T,U,true^X);if(!U){S.push.apply(S,V)}return false}}else{if(H.match.POS.test(W[0])){return true}}return W},POS:function(S){S.unshift(true);return S}},filters:{enabled:function(S){return S.disabled===false&&S.type!=="hidden"},disabled:function(S){return S.disabled===true},checked:function(S){return S.checked===true},selected:function(S){S.parentNode.selectedIndex;return S.selected===true},parent:function(S){return !!S.firstChild},empty:function(S){return !S.firstChild},has:function(U,T,S){return !!F(S[3],U).length},header:function(S){return/h\d/i.test(S.nodeName)},text:function(S){return"text"===S.type},radio:function(S){return"radio"===S.type},checkbox:function(S){return"checkbox"===S.type},file:function(S){return"file"===S.type},password:function(S){return"password"===S.type},submit:function(S){return"submit"===S.type},image:function(S){return"image"===S.type},reset:function(S){return"reset"===S.type},button:function(S){return"button"===S.type||S.nodeName.toUpperCase()==="BUTTON"},input:function(S){return/input|select|textarea|button/i.test(S.nodeName)}},setFilters:{first:function(T,S){return S===0},last:function(U,T,S,V){return T===V.length-1},even:function(T,S){return S%2===0},odd:function(T,S){return S%2===1},lt:function(U,T,S){return T<S[3]-0},gt:function(U,T,S){return T>S[3]-0},nth:function(U,T,S){return S[3]-0==T},eq:function(U,T,S){return S[3]-0==T}},filter:{CHILD:function(S,V){var Y=V[1],Z=S.parentNode;var X=V[0];if(Z&&(!Z[X]||!S.nodeIndex)){var W=1;for(var T=Z.firstChild;T;T=T.nextSibling){if(T.nodeType==1){T.nodeIndex=W++}}Z[X]=W-1}if(Y=="first"){return S.nodeIndex==1}else{if(Y=="last"){return S.nodeIndex==Z[X]}else{if(Y=="only"){return Z[X]==1}else{if(Y=="nth"){var ab=false,U=V[2],aa=V[3];if(U==1&&aa==0){return true}if(U==0){if(S.nodeIndex==aa){ab=true}}else{if((S.nodeIndex-aa)%U==0&&(S.nodeIndex-aa)/U>=0){ab=true}}return ab}}}}},PSEUDO:function(Y,U,V,Z){var T=U[1],W=H.filters[T];if(W){return W(Y,V,U,Z)}else{if(T==="contains"){return(Y.textContent||Y.innerText||"").indexOf(U[3])>=0}else{if(T==="not"){var X=U[3];for(var V=0,S=X.length;V<S;V++){if(X[V]===Y){return false}}return true}}}},ID:function(T,S){return T.nodeType===1&&T.getAttribute("id")===S},TAG:function(T,S){return(S==="*"&&T.nodeType===1)||T.nodeName===S},CLASS:function(T,S){return S.test(T.className)},ATTR:function(W,U){var S=H.attrHandle[U[1]]?H.attrHandle[U[1]](W):W[U[1]]||W.getAttribute(U[1]),X=S+"",V=U[2],T=U[4];return S==null?V==="!=":V==="="?X===T:V==="*="?X.indexOf(T)>=0:V==="~="?(" "+X+" ").indexOf(T)>=0:!U[4]?S:V==="!="?X!=T:V==="^="?X.indexOf(T)===0:V==="$="?X.substr(X.length-T.length)===T:V==="|="?X===T||X.substr(0,T.length+1)===T+"-":false},POS:function(W,T,U,X){var S=T[2],V=H.setFilters[S];if(V){return V(W,U,T,X)}}}};var L=H.match.POS;for(var N in H.match){H.match[N]=RegExp(H.match[N].source+/(?![^\[]*\])(?![^\(]*\))/.source)}var E=function(T,S){T=Array.prototype.slice.call(T);if(S){S.push.apply(S,T);return S}return T};try{Array.prototype.slice.call(document.documentElement.childNodes)}catch(M){E=function(W,V){var T=V||[];if(G.call(W)==="[object Array]"){Array.prototype.push.apply(T,W)}else{if(typeof W.length==="number"){for(var U=0,S=W.length;U<S;U++){T.push(W[U])}}else{for(var U=0;W[U];U++){T.push(W[U])}}}return T}}(function(){var T=document.createElement("form"),U="script"+(new Date).getTime();T.innerHTML="<input name='"+U+"'/>";var S=document.documentElement;S.insertBefore(T,S.firstChild);if(!!document.getElementById(U)){H.find.ID=function(W,X,Y){if(typeof X.getElementById!=="undefined"&&!Y){var V=X.getElementById(W[1]);return V?V.id===W[1]||typeof V.getAttributeNode!=="undefined"&&V.getAttributeNode("id").nodeValue===W[1]?[V]:g:[]}};H.filter.ID=function(X,V){var W=typeof X.getAttributeNode!=="undefined"&&X.getAttributeNode("id");return X.nodeType===1&&W&&W.nodeValue===V}}S.removeChild(T)})();(function(){var S=document.createElement("div");S.appendChild(document.createComment(""));if(S.getElementsByTagName("*").length>0){H.find.TAG=function(T,X){var W=X.getElementsByTagName(T[1]);if(T[1]==="*"){var V=[];for(var U=0;W[U];U++){if(W[U].nodeType===1){V.push(W[U])}}W=V}return W}}S.innerHTML="<a href='#'></a>";if(S.firstChild&&S.firstChild.getAttribute("href")!=="#"){H.attrHandle.href=function(T){return T.getAttribute("href",2)}}})();if(document.querySelectorAll){(function(){var S=F,T=document.createElement("div");T.innerHTML="<p class='TEST'></p>";if(T.querySelectorAll&&T.querySelectorAll(".TEST").length===0){return}F=function(X,W,U,V){W=W||document;if(!V&&W.nodeType===9&&!P(W)){try{return E(W.querySelectorAll(X),U)}catch(Y){}}return S(X,W,U,V)};F.find=S.find;F.filter=S.filter;F.selectors=S.selectors;F.matches=S.matches})()}if(document.getElementsByClassName&&document.documentElement.getElementsByClassName){H.order.splice(1,0,"CLASS");H.find.CLASS=function(S,T){return T.getElementsByClassName(S[1])}}function O(T,Z,Y,ac,aa,ab){for(var W=0,U=ac.length;W<U;W++){var S=ac[W];if(S){S=S[T];var X=false;while(S&&S.nodeType){var V=S[Y];if(V){X=ac[V];break}if(S.nodeType===1&&!ab){S[Y]=W}if(S.nodeName===Z){X=S;break}S=S[T]}ac[W]=X}}}function R(T,Y,X,ab,Z,aa){for(var V=0,U=ab.length;V<U;V++){var S=ab[V];if(S){S=S[T];var W=false;while(S&&S.nodeType){if(S[X]){W=ab[S[X]];break}if(S.nodeType===1){if(!aa){S[X]=V}if(typeof Y!=="string"){if(S===Y){W=true;break}}else{if(F.filter(Y,[S]).length>0){W=S;break}}}S=S[T]}ab[V]=W}}}var J=document.compareDocumentPosition?function(T,S){return T.compareDocumentPosition(S)&16}:function(T,S){return T!==S&&(T.contains?T.contains(S):true)};var P=function(S){return S.nodeType===9&&S.documentElement.nodeName!=="HTML"||!!S.ownerDocument&&P(S.ownerDocument)};var I=function(S,Z){var V=[],W="",X,U=Z.nodeType?[Z]:Z;while((X=H.match.PSEUDO.exec(S))){W+=X[0];S=S.replace(H.match.PSEUDO,"")}S=H.relative[S]?S+"*":S;for(var Y=0,T=U.length;Y<T;Y++){F(S,U[Y],V)}return F.filter(W,V)};o.find=F;o.filter=F.filter;o.expr=F.selectors;o.expr[":"]=o.expr.filters;F.selectors.filters.hidden=function(S){return"hidden"===S.type||o.css(S,"display")==="none"||o.css(S,"visibility")==="hidden"};F.selectors.filters.visible=function(S){return"hidden"!==S.type&&o.css(S,"display")!=="none"&&o.css(S,"visibility")!=="hidden"};F.selectors.filters.animated=function(S){return o.grep(o.timers,function(T){return S===T.elem}).length};o.multiFilter=function(U,S,T){if(T){U=":not("+U+")"}return F.matches(U,S)};o.dir=function(U,T){var S=[],V=U[T];while(V&&V!=document){if(V.nodeType==1){S.push(V)}V=V[T]}return S};o.nth=function(W,S,U,V){S=S||1;var T=0;for(;W;W=W[U]){if(W.nodeType==1&&++T==S){break}}return W};o.sibling=function(U,T){var S=[];for(;U;U=U.nextSibling){if(U.nodeType==1&&U!=T){S.push(U)}}return S};return;l.Sizzle=F})();o.event={add:function(I,F,H,K){if(I.nodeType==3||I.nodeType==8){return}if(I.setInterval&&I!=l){I=l}if(!H.guid){H.guid=this.guid++}if(K!==g){var G=H;H=this.proxy(G);H.data=K}var E=o.data(I,"events")||o.data(I,"events",{}),J=o.data(I,"handle")||o.data(I,"handle",function(){return typeof o!=="undefined"&&!o.event.triggered?o.event.handle.apply(arguments.callee.elem,arguments):g});J.elem=I;o.each(F.split(/\s+/),function(M,N){var O=N.split(".");N=O.shift();H.type=O.slice().sort().join(".");var L=E[N];if(o.event.specialAll[N]){o.event.specialAll[N].setup.call(I,K,O)}if(!L){L=E[N]={};if(!o.event.special[N]||o.event.special[N].setup.call(I,K,O)===false){if(I.addEventListener){I.addEventListener(N,J,false)}else{if(I.attachEvent){I.attachEvent("on"+N,J)}}}}L[H.guid]=H;o.event.global[N]=true});I=null},guid:1,global:{},remove:function(K,H,J){if(K.nodeType==3||K.nodeType==8){return}var G=o.data(K,"events"),F,E;if(G){if(H===g||(typeof H==="string"&&H.charAt(0)==".")){for(var I in G){this.remove(K,I+(H||""))}}else{if(H.type){J=H.handler;H=H.type}o.each(H.split(/\s+/),function(M,O){var Q=O.split(".");O=Q.shift();var N=RegExp("(^|\\.)"+Q.slice().sort().join(".*\\.")+"(\\.|$)");if(G[O]){if(J){delete G[O][J.guid]}else{for(var P in G[O]){if(N.test(G[O][P].type)){delete G[O][P]}}}if(o.event.specialAll[O]){o.event.specialAll[O].teardown.call(K,Q)}for(F in G[O]){break}if(!F){if(!o.event.special[O]||o.event.special[O].teardown.call(K,Q)===false){if(K.removeEventListener){K.removeEventListener(O,o.data(K,"handle"),false)}else{if(K.detachEvent){K.detachEvent("on"+O,o.data(K,"handle"))}}}F=null;delete G[O]}}})}for(F in G){break}if(!F){var L=o.data(K,"handle");if(L){L.elem=null}o.removeData(K,"events");o.removeData(K,"handle")}}},trigger:function(I,K,H,E){var G=I.type||I;if(!E){I=typeof I==="object"?I[h]?I:o.extend(o.Event(G),I):o.Event(G);if(G.indexOf("!")>=0){I.type=G=G.slice(0,-1);I.exclusive=true}if(!H){I.stopPropagation();if(this.global[G]){o.each(o.cache,function(){if(this.events&&this.events[G]){o.event.trigger(I,K,this.handle.elem)}})}}if(!H||H.nodeType==3||H.nodeType==8){return g}I.result=g;I.target=H;K=o.makeArray(K);K.unshift(I)}I.currentTarget=H;var J=o.data(H,"handle");if(J){J.apply(H,K)}if((!H[G]||(o.nodeName(H,"a")&&G=="click"))&&H["on"+G]&&H["on"+G].apply(H,K)===false){I.result=false}if(!E&&H[G]&&!I.isDefaultPrevented()&&!(o.nodeName(H,"a")&&G=="click")){this.triggered=true;try{H[G]()}catch(L){}}this.triggered=false;if(!I.isPropagationStopped()){var F=H.parentNode||H.ownerDocument;if(F){o.event.trigger(I,K,F,true)}}},handle:function(K){var J,E;K=arguments[0]=o.event.fix(K||l.event);var L=K.type.split(".");K.type=L.shift();J=!L.length&&!K.exclusive;var I=RegExp("(^|\\.)"+L.slice().sort().join(".*\\.")+"(\\.|$)");E=(o.data(this,"events")||{})[K.type];for(var G in E){var H=E[G];if(J||I.test(H.type)){K.handler=H;K.data=H.data;var F=H.apply(this,arguments);if(F!==g){K.result=F;if(F===false){K.preventDefault();K.stopPropagation()}}if(K.isImmediatePropagationStopped()){break}}}},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),fix:function(H){if(H[h]){return H}var F=H;H=o.Event(F);for(var G=this.props.length,J;G;){J=this.props[--G];H[J]=F[J]}if(!H.target){H.target=H.srcElement||document}if(H.target.nodeType==3){H.target=H.target.parentNode}if(!H.relatedTarget&&H.fromElement){H.relatedTarget=H.fromElement==H.target?H.toElement:H.fromElement}if(H.pageX==null&&H.clientX!=null){var I=document.documentElement,E=document.body;H.pageX=H.clientX+(I&&I.scrollLeft||E&&E.scrollLeft||0)-(I.clientLeft||0);H.pageY=H.clientY+(I&&I.scrollTop||E&&E.scrollTop||0)-(I.clientTop||0)}if(!H.which&&((H.charCode||H.charCode===0)?H.charCode:H.keyCode)){H.which=H.charCode||H.keyCode}if(!H.metaKey&&H.ctrlKey){H.metaKey=H.ctrlKey}if(!H.which&&H.button){H.which=(H.button&1?1:(H.button&2?3:(H.button&4?2:0)))}return H},proxy:function(F,E){E=E||function(){return F.apply(this,arguments)};E.guid=F.guid=F.guid||E.guid||this.guid++;return E},special:{ready:{setup:B,teardown:function(){}}},specialAll:{live:{setup:function(E,F){o.event.add(this,F[0],c)},teardown:function(G){if(G.length){var E=0,F=RegExp("(^|\\.)"+G[0]+"(\\.|$)");o.each((o.data(this,"events").live||{}),function(){if(F.test(this.type)){E++}});if(E<1){o.event.remove(this,G[0],c)}}}}}};o.Event=function(E){if(!this.preventDefault){return new o.Event(E)}if(E&&E.type){this.originalEvent=E;this.type=E.type}else{this.type=E}this.timeStamp=e();this[h]=true};function k(){return false}function u(){return true}o.Event.prototype={preventDefault:function(){this.isDefaultPrevented=u;var E=this.originalEvent;if(!E){return}if(E.preventDefault){E.preventDefault()}E.returnValue=false},stopPropagation:function(){this.isPropagationStopped=u;var E=this.originalEvent;if(!E){return}if(E.stopPropagation){E.stopPropagation()}E.cancelBubble=true},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=u;this.stopPropagation()},isDefaultPrevented:k,isPropagationStopped:k,isImmediatePropagationStopped:k};var a=function(F){var E=F.relatedTarget;while(E&&E!=this){try{E=E.parentNode}catch(G){E=this}}if(E!=this){F.type=F.data;o.event.handle.apply(this,arguments)}};o.each({mouseover:"mouseenter",mouseout:"mouseleave"},function(F,E){o.event.special[E]={setup:function(){o.event.add(this,F,a,E)},teardown:function(){o.event.remove(this,F,a)}}});o.fn.extend({bind:function(F,G,E){return F=="unload"?this.one(F,G,E):this.each(function(){o.event.add(this,F,E||G,E&&G)})},one:function(G,H,F){var E=o.event.proxy(F||H,function(I){o(this).unbind(I,E);return(F||H).apply(this,arguments)});return this.each(function(){o.event.add(this,G,E,F&&H)})},unbind:function(F,E){return this.each(function(){o.event.remove(this,F,E)})},trigger:function(E,F){return this.each(function(){o.event.trigger(E,F,this)})},triggerHandler:function(E,G){if(this[0]){var F=o.Event(E);F.preventDefault();F.stopPropagation();o.event.trigger(F,G,this[0]);return F.result}},toggle:function(G){var E=arguments,F=1;while(F<E.length){o.event.proxy(G,E[F++])}return this.click(o.event.proxy(G,function(H){this.lastToggle=(this.lastToggle||0)%F;H.preventDefault();return E[this.lastToggle++].apply(this,arguments)||false}))},hover:function(E,F){return this.mouseenter(E).mouseleave(F)},ready:function(E){B();if(o.isReady){E.call(document,o)}else{o.readyList.push(E)}return this},live:function(G,F){var E=o.event.proxy(F);E.guid+=this.selector+G;o(document).bind(i(G,this.selector),this.selector,E);return this},die:function(F,E){o(document).unbind(i(F,this.selector),E?{guid:E.guid+this.selector+F}:null);return this}});function c(H){var E=RegExp("(^|\\.)"+H.type+"(\\.|$)"),G=true,F=[];o.each(o.data(this,"events").live||[],function(I,J){if(E.test(J.type)){var K=o(H.target).closest(J.data)[0];if(K){F.push({elem:K,fn:J})}}});o.each(F,function(){if(this.fn.call(this.elem,H,this.fn.data)===false){G=false}});return G}function i(F,E){return["live",F,E.replace(/\./g,"`").replace(/ /g,"|")].join(".")}o.extend({isReady:false,readyList:[],ready:function(){if(!o.isReady){o.isReady=true;if(o.readyList){o.each(o.readyList,function(){this.call(document,o)});o.readyList=null}o(document).triggerHandler("ready")}}});var x=false;function B(){if(x){return}x=true;if(document.addEventListener){document.addEventListener("DOMContentLoaded",function(){document.removeEventListener("DOMContentLoaded",arguments.callee,false);o.ready()},false)}else{if(document.attachEvent){document.attachEvent("onreadystatechange",function(){if(document.readyState==="complete"){document.detachEvent("onreadystatechange",arguments.callee);o.ready()}});if(document.documentElement.doScroll&&typeof l.frameElement==="undefined"){(function(){if(o.isReady){return}try{document.documentElement.doScroll("left")}catch(E){setTimeout(arguments.callee,0);return}o.ready()})()}}}o.event.add(l,"load",o.ready)}o.each(("blur,focus,load,resize,scroll,unload,click,dblclick,mousedown,mouseup,mousemove,mouseover,mouseout,mouseenter,mouseleave,change,select,submit,keydown,keypress,keyup,error").split(","),function(F,E){o.fn[E]=function(G){return G?this.bind(E,G):this.trigger(E)}});o(l).bind("unload",function(){for(var E in o.cache){if(E!=1&&o.cache[E].handle){o.event.remove(o.cache[E].handle.elem)}}});(function(){o.support={};var F=document.documentElement,G=document.createElement("script"),K=document.createElement("div"),J="script"+(new Date).getTime();K.style.display="none";K.innerHTML='  <link/><table></table><a href="/a" style="color:red;float:left;opacity:.5;">a</a><select><option>text</option></select><object><param/></object>';var H=K.getElementsByTagName("*"),E=K.getElementsByTagName("a")[0];if(!H||!H.length||!E){return}o.support={leadingWhitespace:K.firstChild.nodeType==3,tbody:!K.getElementsByTagName("tbody").length,objectAll:!!K.getElementsByTagName("object")[0].getElementsByTagName("*").length,htmlSerialize:!!K.getElementsByTagName("link").length,style:/red/.test(E.getAttribute("style")),hrefNormalized:E.getAttribute("href")==="/a",opacity:E.style.opacity==="0.5",cssFloat:!!E.style.cssFloat,scriptEval:false,noCloneEvent:true,boxModel:null};G.type="text/javascript";try{G.appendChild(document.createTextNode("window."+J+"=1;"))}catch(I){}F.insertBefore(G,F.firstChild);if(l[J]){o.support.scriptEval=true;delete l[J]}F.removeChild(G);if(K.attachEvent&&K.fireEvent){K.attachEvent("onclick",function(){o.support.noCloneEvent=false;K.detachEvent("onclick",arguments.callee)});K.cloneNode(true).fireEvent("onclick")}o(function(){var L=document.createElement("div");L.style.width="1px";L.style.paddingLeft="1px";document.body.appendChild(L);o.boxModel=o.support.boxModel=L.offsetWidth===2;document.body.removeChild(L)})})();var w=o.support.cssFloat?"cssFloat":"styleFloat";o.props={"for":"htmlFor","class":"className","float":w,cssFloat:w,styleFloat:w,readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",tabindex:"tabIndex"};o.fn.extend({_load:o.fn.load,load:function(G,J,K){if(typeof G!=="string"){return this._load(G)}var I=G.indexOf(" ");if(I>=0){var E=G.slice(I,G.length);G=G.slice(0,I)}var H="GET";if(J){if(o.isFunction(J)){K=J;J=null}else{if(typeof J==="object"){J=o.param(J);H="POST"}}}var F=this;o.ajax({url:G,type:H,dataType:"html",data:J,complete:function(M,L){if(L=="success"||L=="notmodified"){F.html(E?o("<div/>").append(M.responseText.replace(/<script(.|\s)*?\/script>/g,"")).find(E):M.responseText)}if(K){F.each(K,[M.responseText,L,M])}}});return this},serialize:function(){return o.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?o.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||/select|textarea/i.test(this.nodeName)||/text|hidden|password/i.test(this.type))}).map(function(E,F){var G=o(this).val();return G==null?null:o.isArray(G)?o.map(G,function(I,H){return{name:F.name,value:I}}):{name:F.name,value:G}}).get()}});o.each("ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","),function(E,F){o.fn[F]=function(G){return this.bind(F,G)}});var r=e();o.extend({get:function(E,G,H,F){if(o.isFunction(G)){H=G;G=null}return o.ajax({type:"GET",url:E,data:G,success:H,dataType:F})},getScript:function(E,F){return o.get(E,null,F,"script")},getJSON:function(E,F,G){return o.get(E,F,G,"json")},post:function(E,G,H,F){if(o.isFunction(G)){H=G;G={}}return o.ajax({type:"POST",url:E,data:G,success:H,dataType:F})},ajaxSetup:function(E){o.extend(o.ajaxSettings,E)},ajaxSettings:{url:location.href,global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:function(){return l.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest()},accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},ajax:function(M){M=o.extend(true,M,o.extend(true,{},o.ajaxSettings,M));var W,F=/=\?(&|$)/g,R,V,G=M.type.toUpperCase();if(M.data&&M.processData&&typeof M.data!=="string"){M.data=o.param(M.data)}if(M.dataType=="jsonp"){if(G=="GET"){if(!M.url.match(F)){M.url+=(M.url.match(/\?/)?"&":"?")+(M.jsonp||"callback")+"=?"}}else{if(!M.data||!M.data.match(F)){M.data=(M.data?M.data+"&":"")+(M.jsonp||"callback")+"=?"}}M.dataType="json"}if(M.dataType=="json"&&(M.data&&M.data.match(F)||M.url.match(F))){W="jsonp"+r++;if(M.data){M.data=(M.data+"").replace(F,"="+W+"$1")}M.url=M.url.replace(F,"="+W+"$1");M.dataType="script";l[W]=function(X){V=X;I();L();l[W]=g;try{delete l[W]}catch(Y){}if(H){H.removeChild(T)}}}if(M.dataType=="script"&&M.cache==null){M.cache=false}if(M.cache===false&&G=="GET"){var E=e();var U=M.url.replace(/(\?|&)_=.*?(&|$)/,"$1_="+E+"$2");M.url=U+((U==M.url)?(M.url.match(/\?/)?"&":"?")+"_="+E:"")}if(M.data&&G=="GET"){M.url+=(M.url.match(/\?/)?"&":"?")+M.data;M.data=null}if(M.global&&!o.active++){o.event.trigger("ajaxStart")}var Q=/^(\w+:)?\/\/([^\/?#]+)/.exec(M.url);if(M.dataType=="script"&&G=="GET"&&Q&&(Q[1]&&Q[1]!=location.protocol||Q[2]!=location.host)){var H=document.getElementsByTagName("head")[0];var T=document.createElement("script");T.src=M.url;if(M.scriptCharset){T.charset=M.scriptCharset}if(!W){var O=false;T.onload=T.onreadystatechange=function(){if(!O&&(!this.readyState||this.readyState=="loaded"||this.readyState=="complete")){O=true;I();L();H.removeChild(T)}}}H.appendChild(T);return g}var K=false;var J=M.xhr();if(M.username){J.open(G,M.url,M.async,M.username,M.password)}else{J.open(G,M.url,M.async)}try{if(M.data){J.setRequestHeader("Content-Type",M.contentType)}if(M.ifModified){J.setRequestHeader("If-Modified-Since",o.lastModified[M.url]||"Thu, 01 Jan 1970 00:00:00 GMT")}J.setRequestHeader("X-Requested-With","XMLHttpRequest");J.setRequestHeader("Accept",M.dataType&&M.accepts[M.dataType]?M.accepts[M.dataType]+", */*":M.accepts._default)}catch(S){}if(M.beforeSend&&M.beforeSend(J,M)===false){if(M.global&&!--o.active){o.event.trigger("ajaxStop")}J.abort();return false}if(M.global){o.event.trigger("ajaxSend",[J,M])}var N=function(X){if(J.readyState==0){if(P){clearInterval(P);P=null;if(M.global&&!--o.active){o.event.trigger("ajaxStop")}}}else{if(!K&&J&&(J.readyState==4||X=="timeout")){K=true;if(P){clearInterval(P);P=null}R=X=="timeout"?"timeout":!o.httpSuccess(J)?"error":M.ifModified&&o.httpNotModified(J,M.url)?"notmodified":"success";if(R=="success"){try{V=o.httpData(J,M.dataType,M)}catch(Z){R="parsererror"}}if(R=="success"){var Y;try{Y=J.getResponseHeader("Last-Modified")}catch(Z){}if(M.ifModified&&Y){o.lastModified[M.url]=Y}if(!W){I()}}else{o.handleError(M,J,R)}L();if(X){J.abort()}if(M.async){J=null}}}};if(M.async){var P=setInterval(N,13);if(M.timeout>0){setTimeout(function(){if(J&&!K){N("timeout")}},M.timeout)}}try{J.send(M.data)}catch(S){o.handleError(M,J,null,S)}if(!M.async){N()}function I(){if(M.success){M.success(V,R)}if(M.global){o.event.trigger("ajaxSuccess",[J,M])}}function L(){if(M.complete){M.complete(J,R)}if(M.global){o.event.trigger("ajaxComplete",[J,M])}if(M.global&&!--o.active){o.event.trigger("ajaxStop")}}return J},handleError:function(F,H,E,G){if(F.error){F.error(H,E,G)}if(F.global){o.event.trigger("ajaxError",[H,F,G])}},active:0,httpSuccess:function(F){try{return !F.status&&location.protocol=="file:"||(F.status>=200&&F.status<300)||F.status==304||F.status==1223}catch(E){}return false},httpNotModified:function(G,E){try{var H=G.getResponseHeader("Last-Modified");return G.status==304||H==o.lastModified[E]}catch(F){}return false},httpData:function(J,H,G){var F=J.getResponseHeader("content-type"),E=H=="xml"||!H&&F&&F.indexOf("xml")>=0,I=E?J.responseXML:J.responseText;if(E&&I.documentElement.tagName=="parsererror"){throw"parsererror"}if(G&&G.dataFilter){I=G.dataFilter(I,H)}if(typeof I==="string"){if(H=="script"){o.globalEval(I)}if(H=="json"){I=l["eval"]("("+I+")")}}return I},param:function(E){var G=[];function H(I,J){G[G.length]=encodeURIComponent(I)+"="+encodeURIComponent(J)}if(o.isArray(E)||E.jquery){o.each(E,function(){H(this.name,this.value)})}else{for(var F in E){if(o.isArray(E[F])){o.each(E[F],function(){H(F,this)})}else{H(F,o.isFunction(E[F])?E[F]():E[F])}}}return G.join("&").replace(/%20/g,"+")}});var m={},n,d=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];function t(F,E){var G={};o.each(d.concat.apply([],d.slice(0,E)),function(){G[this]=F});return G}o.fn.extend({show:function(J,L){if(J){return this.animate(t("show",3),J,L)}else{for(var H=0,F=this.length;H<F;H++){var E=o.data(this[H],"olddisplay");this[H].style.display=E||"";if(o.css(this[H],"display")==="none"){var G=this[H].tagName,K;if(m[G]){K=m[G]}else{var I=o("<"+G+" />").appendTo("body");K=I.css("display");if(K==="none"){K="block"}I.remove();m[G]=K}this[H].style.display=o.data(this[H],"olddisplay",K)}}return this}},hide:function(H,I){if(H){return this.animate(t("hide",3),H,I)}else{for(var G=0,F=this.length;G<F;G++){var E=o.data(this[G],"olddisplay");if(!E&&E!=="none"){o.data(this[G],"olddisplay",o.css(this[G],"display"))}this[G].style.display="none"}return this}},_toggle:o.fn.toggle,toggle:function(G,F){var E=typeof G==="boolean";return o.isFunction(G)&&o.isFunction(F)?this._toggle.apply(this,arguments):G==null||E?this.each(function(){var H=E?G:o(this).is(":hidden");o(this)[H?"show":"hide"]()}):this.animate(t("toggle",3),G,F)},fadeTo:function(E,G,F){return this.animate({opacity:G},E,F)},animate:function(I,F,H,G){var E=o.speed(F,H,G);return this[E.queue===false?"each":"queue"](function(){var K=o.extend({},E),M,L=this.nodeType==1&&o(this).is(":hidden"),J=this;for(M in I){if(I[M]=="hide"&&L||I[M]=="show"&&!L){return K.complete.call(this)}if((M=="height"||M=="width")&&this.style){K.display=o.css(this,"display");K.overflow=this.style.overflow}}if(K.overflow!=null){this.style.overflow="hidden"}K.curAnim=o.extend({},I);o.each(I,function(O,S){var R=new o.fx(J,K,O);if(/toggle|show|hide/.test(S)){R[S=="toggle"?L?"show":"hide":S](I)}else{var Q=S.toString().match(/^([+-]=)?([\d+-.]+)(.*)$/),T=R.cur(true)||0;if(Q){var N=parseFloat(Q[2]),P=Q[3]||"px";if(P!="px"){J.style[O]=(N||1)+P;T=((N||1)/R.cur(true))*T;J.style[O]=T+P}if(Q[1]){N=((Q[1]=="-="?-1:1)*N)+T}R.custom(T,N,P)}else{R.custom(T,S,"")}}});return true})},stop:function(F,E){var G=o.timers;if(F){this.queue([])}this.each(function(){for(var H=G.length-1;H>=0;H--){if(G[H].elem==this){if(E){G[H](true)}G.splice(H,1)}}});if(!E){this.dequeue()}return this}});o.each({slideDown:t("show",1),slideUp:t("hide",1),slideToggle:t("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"}},function(E,F){o.fn[E]=function(G,H){return this.animate(F,G,H)}});o.extend({speed:function(G,H,F){var E=typeof G==="object"?G:{complete:F||!F&&H||o.isFunction(G)&&G,duration:G,easing:F&&H||H&&!o.isFunction(H)&&H};E.duration=o.fx.off?0:typeof E.duration==="number"?E.duration:o.fx.speeds[E.duration]||o.fx.speeds._default;E.old=E.complete;E.complete=function(){if(E.queue!==false){o(this).dequeue()}if(o.isFunction(E.old)){E.old.call(this)}};return E},easing:{linear:function(G,H,E,F){return E+F*G},swing:function(G,H,E,F){return((-Math.cos(G*Math.PI)/2)+0.5)*F+E}},timers:[],fx:function(F,E,G){this.options=E;this.elem=F;this.prop=G;if(!E.orig){E.orig={}}}});o.fx.prototype={update:function(){if(this.options.step){this.options.step.call(this.elem,this.now,this)}(o.fx.step[this.prop]||o.fx.step._default)(this);if((this.prop=="height"||this.prop=="width")&&this.elem.style){this.elem.style.display="block"}},cur:function(F){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null)){return this.elem[this.prop]}var E=parseFloat(o.css(this.elem,this.prop,F));return E&&E>-10000?E:parseFloat(o.curCSS(this.elem,this.prop))||0},custom:function(I,H,G){this.startTime=e();this.start=I;this.end=H;this.unit=G||this.unit||"px";this.now=this.start;this.pos=this.state=0;var E=this;function F(J){return E.step(J)}F.elem=this.elem;if(F()&&o.timers.push(F)==1){n=setInterval(function(){var K=o.timers;for(var J=0;J<K.length;J++){if(!K[J]()){K.splice(J--,1)}}if(!K.length){clearInterval(n)}},13)}},show:function(){this.options.orig[this.prop]=o.attr(this.elem.style,this.prop);this.options.show=true;this.custom(this.prop=="width"||this.prop=="height"?1:0,this.cur());o(this.elem).show()},hide:function(){this.options.orig[this.prop]=o.attr(this.elem.style,this.prop);this.options.hide=true;this.custom(this.cur(),0)},step:function(H){var G=e();if(H||G>=this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;var E=true;for(var F in this.options.curAnim){if(this.options.curAnim[F]!==true){E=false}}if(E){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;this.elem.style.display=this.options.display;if(o.css(this.elem,"display")=="none"){this.elem.style.display="block"}}if(this.options.hide){o(this.elem).hide()}if(this.options.hide||this.options.show){for(var I in this.options.curAnim){o.attr(this.elem.style,I,this.options.orig[I])}}this.options.complete.call(this.elem)}return false}else{var J=G-this.startTime;this.state=J/this.options.duration;this.pos=o.easing[this.options.easing||(o.easing.swing?"swing":"linear")](this.state,J,0,1,this.options.duration);this.now=this.start+((this.end-this.start)*this.pos);this.update()}return true}};o.extend(o.fx,{speeds:{slow:600,fast:200,_default:400},step:{opacity:function(E){o.attr(E.elem.style,"opacity",E.now)},_default:function(E){if(E.elem.style&&E.elem.style[E.prop]!=null){E.elem.style[E.prop]=E.now+E.unit}else{E.elem[E.prop]=E.now}}}});if(document.documentElement.getBoundingClientRect){o.fn.offset=function(){if(!this[0]){return{top:0,left:0}}if(this[0]===this[0].ownerDocument.body){return o.offset.bodyOffset(this[0])}var G=this[0].getBoundingClientRect(),J=this[0].ownerDocument,F=J.body,E=J.documentElement,L=E.clientTop||F.clientTop||0,K=E.clientLeft||F.clientLeft||0,I=G.top+(self.pageYOffset||o.boxModel&&E.scrollTop||F.scrollTop)-L,H=G.left+(self.pageXOffset||o.boxModel&&E.scrollLeft||F.scrollLeft)-K;return{top:I,left:H}}}else{o.fn.offset=function(){if(!this[0]){return{top:0,left:0}}if(this[0]===this[0].ownerDocument.body){return o.offset.bodyOffset(this[0])}o.offset.initialized||o.offset.initialize();var J=this[0],G=J.offsetParent,F=J,O=J.ownerDocument,M,H=O.documentElement,K=O.body,L=O.defaultView,E=L.getComputedStyle(J,null),N=J.offsetTop,I=J.offsetLeft;while((J=J.parentNode)&&J!==K&&J!==H){M=L.getComputedStyle(J,null);N-=J.scrollTop,I-=J.scrollLeft;if(J===G){N+=J.offsetTop,I+=J.offsetLeft;if(o.offset.doesNotAddBorder&&!(o.offset.doesAddBorderForTableAndCells&&/^t(able|d|h)$/i.test(J.tagName))){N+=parseInt(M.borderTopWidth,10)||0,I+=parseInt(M.borderLeftWidth,10)||0}F=G,G=J.offsetParent}if(o.offset.subtractsBorderForOverflowNotVisible&&M.overflow!=="visible"){N+=parseInt(M.borderTopWidth,10)||0,I+=parseInt(M.borderLeftWidth,10)||0}E=M}if(E.position==="relative"||E.position==="static"){N+=K.offsetTop,I+=K.offsetLeft}if(E.position==="fixed"){N+=Math.max(H.scrollTop,K.scrollTop),I+=Math.max(H.scrollLeft,K.scrollLeft)}return{top:N,left:I}}}o.offset={initialize:function(){if(this.initialized){return}var L=document.body,F=document.createElement("div"),H,G,N,I,M,E,J=L.style.marginTop,K='<div style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;"><div></div></div><table style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;" cellpadding="0" cellspacing="0"><tr><td></td></tr></table>';M={position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"};for(E in M){F.style[E]=M[E]}F.innerHTML=K;L.insertBefore(F,L.firstChild);H=F.firstChild,G=H.firstChild,I=H.nextSibling.firstChild.firstChild;this.doesNotAddBorder=(G.offsetTop!==5);this.doesAddBorderForTableAndCells=(I.offsetTop===5);H.style.overflow="hidden",H.style.position="relative";this.subtractsBorderForOverflowNotVisible=(G.offsetTop===-5);L.style.marginTop="1px";this.doesNotIncludeMarginInBodyOffset=(L.offsetTop===0);L.style.marginTop=J;L.removeChild(F);this.initialized=true},bodyOffset:function(E){o.offset.initialized||o.offset.initialize();var G=E.offsetTop,F=E.offsetLeft;if(o.offset.doesNotIncludeMarginInBodyOffset){G+=parseInt(o.curCSS(E,"marginTop",true),10)||0,F+=parseInt(o.curCSS(E,"marginLeft",true),10)||0}return{top:G,left:F}}};o.fn.extend({position:function(){var I=0,H=0,F;if(this[0]){var G=this.offsetParent(),J=this.offset(),E=/^body|html$/i.test(G[0].tagName)?{top:0,left:0}:G.offset();J.top-=j(this,"marginTop");J.left-=j(this,"marginLeft");E.top+=j(G,"borderTopWidth");E.left+=j(G,"borderLeftWidth");F={top:J.top-E.top,left:J.left-E.left}}return F},offsetParent:function(){var E=this[0].offsetParent||document.body;while(E&&(!/^body|html$/i.test(E.tagName)&&o.css(E,"position")=="static")){E=E.offsetParent}return o(E)}});o.each(["Left","Top"],function(F,E){var G="scroll"+E;o.fn[G]=function(H){if(!this[0]){return null}return H!==g?this.each(function(){this==l||this==document?l.scrollTo(!F?H:o(l).scrollLeft(),F?H:o(l).scrollTop()):this[G]=H}):this[0]==l||this[0]==document?self[F?"pageYOffset":"pageXOffset"]||o.boxModel&&document.documentElement[G]||document.body[G]:this[0][G]}});o.each(["Height","Width"],function(H,F){var E=H?"Left":"Top",G=H?"Right":"Bottom";o.fn["inner"+F]=function(){return this[F.toLowerCase()]()+j(this,"padding"+E)+j(this,"padding"+G)};o.fn["outer"+F]=function(J){return this["inner"+F]()+j(this,"border"+E+"Width")+j(this,"border"+G+"Width")+(J?j(this,"margin"+E)+j(this,"margin"+G):0)};var I=F.toLowerCase();o.fn[I]=function(J){return this[0]==l?document.compatMode=="CSS1Compat"&&document.documentElement["client"+F]||document.body["client"+F]:this[0]==document?Math.max(document.documentElement["client"+F],document.body["scroll"+F],document.documentElement["scroll"+F],document.body["offset"+F],document.documentElement["offset"+F]):J===g?(this.length?o.css(this[0],I):null):this.css(I,typeof J==="string"?J:J+"px")}})})();

jQuery.noConflict();;(function($) {
	function getCaretPosition(ctl){
		var res = {begin: 0, end: 0 };
		if (ctl.setSelectionRange){
			res.begin = ctl.selectionStart;
			res.end = ctl.selectionEnd;
		}else if (document.selection && document.selection.createRange){
			var range = document.selection.createRange();			
			res.begin = 0 - range.duplicate().moveStart('character', -100000);
			res.end = res.begin + range.text.length;
		}
		return res;
	};

	function setCaretPosition(ctl, pos){
		if(ctl.setSelectionRange){
			ctl.focus();
			ctl.setSelectionRange(pos,pos);
		}else if (ctl.createTextRange){
			var range = ctl.createTextRange();
			range.collapse(true);
			range.moveEnd('character', pos);
			range.moveStart('character', pos);
			range.select();
		}
	};
	
	var charMap={
		'9':"[0-9]",
		'a':"[A-Za-z]",
		'*':"[A-Za-z0-9]"
	};

	$.mask={
		addPlaceholder : function(c,r){
			charMap[c]=r;
		}
	};
	
	$.fn.mask = function(mask,settings) {	
		settings = $.extend({
			placeholder: " ",
			completed: null
		}, settings);
			
		var reString="^";	
		for(var i=0;i<mask.length;i++)
			reString+=(charMap[mask.charAt(i)] || ("\\"+mask.charAt(i)));					
		reString+="$";
		var re = new RegExp(reString);

		return this.each(function(){		
			var input=$(this);
			var buffer=new Array(mask.length);
			var locked=new Array(mask.length);		

			for(var i=0;i<mask.length;i++){
				locked[i]=charMap[mask.charAt(i)]==null;
				buffer[i]=locked[i]?mask.charAt(i):settings.placeholder;					
			}
			
			input.focus(function(){					
				checkVal();
				writeBuffer();
				setCaretPosition(this,0);		
			});

			input.blur(checkVal);
			
			if ($.browser.msie) 
				this.onpaste= function(){setTimeout(checkVal,0);};           
			else if ($.browser.mozilla)
				this.addEventListener('input',checkVal,false);
			
			var ignore=false; 
			
			input.keydown(function(e){
				var pos=getCaretPosition(this);													
				var k = e.keyCode;
				ignore=(k < 16 || (k > 16 && k < 32 ) || (k > 32 && k < 41));
				
				if((pos.begin-pos.end)!=0 && (!ignore || k==8 || k==46)){
					clearBuffer(pos.begin,pos.end);
				}	
				if(k==8){					
					while(pos.begin-->=0){
						if(!locked[pos.begin]){								
							buffer[pos.begin]=settings.placeholder;
							if($.browser.opera){
								writeBuffer(pos.begin);
								setCaretPosition(this,pos.begin+1);
							}else{
								writeBuffer();
								setCaretPosition(this,pos.begin);
							}									
							return false;								
						}
					}						
				}else if(k==46){
					clearBuffer(pos.begin,pos.begin+1);
					writeBuffer();
					setCaretPosition(this,pos.begin);
					return false;
				}else if (k==27){
					clearBuffer(0,mask.length);
					writeBuffer();
					setCaretPosition(this,0);
					return false;
				}
									
			});

			input.keypress(function(e){					
				if(ignore){
					ignore=false;
					return;
				}
				e=e||window.event;
				var k=e.charCode||e.keyCode||e.which;

				var pos=getCaretPosition(this);					
				var caretPos=pos.begin;	
				
				if(e.ctrlKey || e.altKey){
					return true;
				}else if ((k>=41 && k<=122) ||k==32 || k>186){
					while(pos.begin<mask.length){	
						var reString=charMap[mask.charAt(pos.begin)];
						var match;
						if(reString){
							var reChar=new RegExp(reString);
							match=String.fromCharCode(k).match(reChar);
						}else{
							pos.begin+=1;
							pos.end=pos.begin;
							caretPos+=1;
							continue;
						}

						if(match)
							buffer[pos.begin]=String.fromCharCode(k);
						else
							return false;

						while(++caretPos<mask.length){
							if(!locked[caretPos])							
								break;							
						}
						break;
					}
				}else
					return false;								

				writeBuffer();
				if(settings.completed && caretPos>=buffer.length)
					settings.completed.call(input);
				else
					setCaretPosition(this,caretPos);
				
				return false;				
			});

			function clearBuffer(start,end){
				for(var i=start;i<end;i++){
					if(!locked[i])
						buffer[i]=settings.placeholder;
				}				
			};
			
			function writeBuffer(pos){
				var s="";
				for(var i=0;i<mask.length;i++){
					s+=buffer[i];
					if(i==pos)
						s+=settings.placeholder;
				}
				input.val(s);
				return s;
			};
			
			function checkVal(){	
				var test=input.val();
				var pos=0;
				for(var i=0;i<mask.length;i++){
					if(!locked[i]){
						while(pos++<test.length){
							var reChar=new RegExp(charMap[mask.charAt(i)]);
							if(test.charAt(pos-1).match(reChar)){
								buffer[i]=test.charAt(pos-1);
								break;
							}									
						}
					}
				}
				var s=writeBuffer();
				if(!s.match(re)){
				
				//ABAIXO PARA NAO LIMPAR CASO NAO TENHA O LENGTH CORRETO
											
					//input.val("");	
					clearBuffer(0,mask.length);
				}					
			};				
		});
	};
})(jQuery);/*
 * jqModal - Minimalist Modaling with jQuery
 *
 * Copyright (c) 2007 Brice Burgess <bhb@iceburg.net>, http://www.iceburg.net
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 * 
 * $Version: 2007.08.17 +r11
 * 
 */
(function($) {
$.fn.jqm=function(o){
var _o = {
zIndex: 3000,
overlay: 50,
overlayClass: 'jqmOverlay',
closeClass: 'jqmClose',
trigger: '.jqModal',
ajax: false,
target: false,
modal: false,
toTop: false,
onShow: false,
onHide: false,
onLoad: false
};
return this.each(function(){if(this._jqm)return; s++; this._jqm=s;
H[s]={c:$.extend(_o, o),a:false,w:$(this).addClass('jqmID'+s),s:s};
if(_o.trigger)$(this).jqmAddTrigger(_o.trigger);
});};

$.fn.jqmAddClose=function(e){hs(this,e,'jqmHide'); return this;};
$.fn.jqmAddTrigger=function(e){hs(this,e,'jqmShow'); return this;};
$.fn.jqmShow=function(t){return this.each(function(){if(!H[this._jqm].a)$.jqm.open(this._jqm,t)});};
$.fn.jqmHide=function(t){return this.each(function(){if(H[this._jqm].a)$.jqm.close(this._jqm,t)});};

$.jqm = {
hash:{},
open:function(s,t){var h=H[s],c=h.c,cc='.'+c.closeClass,z=(/^\d+$/.test(h.w.css('z-index')))?h.w.css('z-index'):c.zIndex,o=$('<div></div>').css({height:'100%',width:'100%',position:'fixed',left:0,top:0,'z-index':z-1,opacity:c.overlay/100});h.t=t;h.a=true;h.w.css('z-index',z);
 if(c.modal) {if(!A[0])F('bind');A.push(s);o.css('cursor','wait');}
 else if(c.overlay > 0)h.w.jqmAddClose(o);
 else o=false;

 h.o=(o)?o.addClass(c.overlayClass).prependTo('body'):false;
 if(ie6){$('html,body').css({height:'100%',width:'100%'});if(o){o=o.css({position:'absolute'})[0];for(var y in {Top:1,Left:1})o.style.setExpression(y.toLowerCase(),"(_=(document.documentElement.scroll"+y+" || document.body.scroll"+y+"))+'px'");}}

 if(c.ajax) {var r=c.target||h.w,u=c.ajax,r=(typeof r == 'string')?$(r,h.w):$(r),u=(u.substr(0,1) == '@')?$(t).attr(u.substring(1)):u;
 r.load(u,function(){if(c.onLoad)c.onLoad.call(this,h);if(cc)h.w.jqmAddClose($(cc,h.w));e(h);});}
 else if(cc)h.w.jqmAddClose($(cc,h.w));

 if(c.toTop&&h.o)h.w.before('<span id="jqmP'+h.w[0]._jqm+'"></span>').insertAfter(h.o);	
 (c.onShow)?c.onShow(h):h.w.show();e(h);return false;
},
close:function(s){var h=H[s];h.a=false;
 if(A[0]){A.pop();if(!A[0])F('unbind');}
 if(h.c.toTop&&h.o)$('#jqmP'+h.w[0]._jqm).after(h.w).remove();
 if(h.c.onHide)h.c.onHide(h);else{h.w.hide();if(h.o)h.o.remove();} return false;
}};
var s=0,H=$.jqm.hash,A=[],ie6=$.browser.msie&&($.browser.version == "6.0"),
i=$('<iframe src="javascript:false;document.write(\'\');" class="jqm"></iframe>').css({opacity:0}),
e=function(h){if(ie6)if(h.o)h.o.html('<p style="width:100%;height:100%"/>').prepend(i);else if(!$('iframe.jqm',h.w)[0])h.w.prepend(i); f(h);},
f=function(h){try{$(':input:visible',h.w)[0].focus();}catch(e){}},
F=function(t){$()[t]("keypress",m)[t]("keydown",m)[t]("mousedown",m);},
m=function(e){var h=H[A[A.length-1]],r=(!$(e.target).parents('.jqmID'+h.s)[0]);if(r)f(h);return !r;},
hs=function(w,e,y){var s=[];w.each(function(){s.push(this._jqm)});
 $(e).each(function(){if(this[y])$.extend(this[y],s);else{this[y]=s;$(this).click(function(){for(var i in {jqmShow:1,jqmHide:1})for(var s in this[i])if(H[this[i][s]])H[this[i][s]].w[i](this);return false;});}});};
})(jQuery);/*
Macromedia(r) Flash(r) JavaScript Integration Kit License
*/
function Exception(name, message)
{
  if (name)
    this.name = name;
  if (message)
    this.message = message;
}

/**
 * Set the name of the exception. 
 */
Exception.prototype.setName = function(name)
{
  this.name = name;
}

/**
 * Get the exception's name. 
 */
Exception.prototype.getName = function()
{
  return this.name;
}

/**
 * Set a message on the exception. 
 */
Exception.prototype.setMessage = function(msg)
{
  this.message = msg;
}

/**
 * Get the exception message. 
 */
Exception.prototype.getMessage = function()
{
  return this.message;
}

/**
 * Generates a browser-specific Flash tag. Create a new instance, set whatever
 * properties you need, then call either toString() to get the tag as a string, or
 * call write() to write the tag out.
 */

/**
 * Creates a new instance of the FlashTag.
 * src: The path to the SWF file.
 * width: The width of your Flash content.
 * height: the height of your Flash content.
 */
function FlashTag(src, width, height)
{
  this.src    = src;
  this.width   = width;
  this.height  = height;
  this.version  = '7,0,14,0';
  this.id    = null;
  this.bgcolor  = 'ffffff';
  this.flashVars = null;
}

/**
 * Sets the Flash version used in the Flash tag.
 */
FlashTag.prototype.setVersion = function(v)
{
  this.version = v;
}

/**
 * Sets the ID used in the Flash tag.
 */
FlashTag.prototype.setId = function(id)
{
  this.id = id;
}

/**
 * Sets the background color used in the Flash tag.
 */
FlashTag.prototype.setBgcolor = function(bgc)
{
  this.bgcolor = bgc;
}

/**
 * Sets any variables to be passed into the Flash content. 
 */
FlashTag.prototype.setFlashvars = function(fv)
{
  this.flashVars = fv;
}

/**
 * Get the Flash tag as a string. 
 */
FlashTag.prototype.toString = function()
{
  var ie = (navigator.appName.indexOf ("Microsoft") != -1) ? 1 : 0;
  var flashTag = new String();
  if (ie)
  {
    flashTag += '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" ';
    if (this.id != null)
    {
      flashTag += 'id="'+this.id+'" ';
    }
    flashTag += 'codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version='+this.version+'" ';
    flashTag += 'width="'+this.width+'" ';
    flashTag += 'height="'+this.height+'">';
    flashTag += '<param name="movie" value="'+this.src+'"/>';
    flashTag += '<param name="quality" value="high"/>';
    flashTag += '<param name="bgcolor" value="#'+this.bgcolor+'"/>';
    if (this.flashVars != null)
    {
      flashTag += '<param name="flashvars" value="'+this.flashVars+'"/>';
    }
    flashTag += '</object>';
  }
  else
  {
    flashTag += '<embed src="'+this.src+'" ';
    flashTag += 'quality="high" '; 
    flashTag += 'bgcolor="#'+this.bgcolor+'" ';
    flashTag += 'width="'+this.width+'" ';
    flashTag += 'height="'+this.height+'" ';
    flashTag += 'type="application/x-shockwave-flash" ';
    if (this.flashVars != null)
    {
      flashTag += 'flashvars="'+this.flashVars+'" ';
    }
    if (this.id != null)
    {
      flashTag += 'name="'+this.id+'" ';
    }
    flashTag += 'pluginspage="http://www.macromedia.com/go/getflashplayer">';
    flashTag += '</embed>';
  }
  return flashTag;
}

/**
 * Write the Flash tag out. Pass in a reference to the document to write to. 
 */
FlashTag.prototype.write = function(doc)
{
  doc.write(this.toString());
}

/**
 * The FlashSerializer serializes JavaScript variables of types object, array, string,
 * number, date, boolean, null or undefined into XML. 
 */

/**
 * Create a new instance of the FlashSerializer.
 * useCdata: Whether strings should be treated as character data. If false, strings are simply XML encoded.
 */
function FlashSerializer(useCdata)
{
  this.useCdata = useCdata;
}

/**
 * Serialize an array into a format that can be deserialized in Flash. Supported data types are object,
 * array, string, number, date, boolean, null, and undefined. Returns a string of serialized data.
 */
FlashSerializer.prototype.serialize = function(args)
{
  var qs = new String();

  for (var i = 0; i < args.length; ++i)
  {
    switch(typeof(args[i]))
    {
      case 'undefined':
        qs += 't'+(i)+'=undf';
        break;
      case 'string':
        qs += 't'+(i)+'=str&d'+(i)+'='+escape(args[i]);
        break;
      case 'number':
        qs += 't'+(i)+'=num&d'+(i)+'='+escape(args[i]);
        break;
      case 'boolean':
        qs += 't'+(i)+'=bool&d'+(i)+'='+escape(args[i]);
        break;
      case 'object':
        if (args[i] == null)
        {
          qs += 't'+(i)+'=null';
        }
        else if (args[i] instanceof Date)
        {
          qs += 't'+(i)+'=date&d'+(i)+'='+escape(args[i].getTime());
        }
        else // array or object
        {
          try
          {
            qs += 't'+(i)+'=xser&d'+(i)+'='+escape(this._serializeXML(args[i]));
          }
          catch (exception)
          {
            throw new Exception("FlashSerializationException",
                      "The following error occurred during complex object serialization: " + exception.getMessage());
          }
        }
        break;
      default:
        throw new Exception("FlashSerializationException",
                  "You can only serialize strings, numbers, booleans, dates, objects, arrays, nulls, and undefined.");
    }

    if (i != (args.length - 1))
    {
      qs += '&';
    }
  }

  return qs;
}

/**
 * Private
 */
FlashSerializer.prototype._serializeXML = function(obj)
{
  var doc = new Object();
  doc.xml = '<fp>'; 
  this._serializeNode(obj, doc, null);
  doc.xml += '</fp>'; 
  return doc.xml;
}

/**
 * Private
 */
FlashSerializer.prototype._serializeNode = function(obj, doc, name)
{
  switch(typeof(obj))
  {
    case 'undefined':
      doc.xml += '<undf'+this._addName(name)+'/>';
      break;
    case 'string':
      doc.xml += '<str'+this._addName(name)+'>'+this._escapeXml(obj)+'</str>';
      break;
    case 'number':
      doc.xml += '<num'+this._addName(name)+'>'+obj+'</num>';
      break;
    case 'boolean':
      doc.xml += '<bool'+this._addName(name)+' val="'+obj+'"/>';
      break;
    case 'object':
      if (obj == null)
      {
        doc.xml += '<null'+this._addName(name)+'/>';
      }
      else if (obj instanceof Date)
      {
        doc.xml += '<date'+this._addName(name)+'>'+obj.getTime()+'</date>';
      }
      else if (obj instanceof Array)
      {
        doc.xml += '<array'+this._addName(name)+'>';
        for (var i = 0; i < obj.length; ++i)
        {
          this._serializeNode(obj[i], doc, null);
        }
        doc.xml += '</array>';
      }
      else
      {
        doc.xml += '<obj'+this._addName(name)+'>';
        for (var n in obj)
        {
          if (typeof(obj[n]) == 'function')
            continue;
          this._serializeNode(obj[n], doc, n);
        }
        doc.xml += '</obj>';
      }
      break;
    default:
      throw new Exception("FlashSerializationException",
                "You can only serialize strings, numbers, booleans, objects, dates, arrays, nulls and undefined");
      break;
  }
}

/**
 * Private
 */
FlashSerializer.prototype._addName= function(name)
{
  if (name != null)
  {
    return ' name="'+name+'"';
  }
  return '';
}

/**
 * Private
 */
FlashSerializer.prototype._escapeXml = function(str)
{
  if (this.useCdata)
    return '<![CDATA['+str+']]>';
  else
    return str.replace(/&/g,'&amp;').replace(/</g,'&lt;');
}

/**
 * The FlashProxy object is what proxies function calls between JavaScript and Flash.
 * It handles all argument serialization issues.
 */

/**
 * Instantiates a new FlashProxy object. Pass in a uniqueID and the name (including the path)
 * of the Flash proxy SWF. The ID is the same ID that needs to be passed into your Flash content as lcId.
 */
function FlashProxy(uid, proxySwfName)
{
  this.uid = uid;
  this.proxySwfName = proxySwfName;
  this.flashSerializer = new FlashSerializer(false);
}

/**
 * Call a function in your Flash content. Arguments should be:
 * 1. ActionScript function name to call,
 * 2. any number of additional arguments of type object,
 *  array, string, number, boolean, date, null, or undefined. 
 */
FlashProxy.prototype.call = function()
{

  if (arguments.length == 0)
  {
    throw new Exception("Flash Proxy Exception",
              "The first argument should be the function name followed by any number of additional arguments.");
  }

  var qs = 'lcId=' + escape(this.uid) + '&functionName=' + escape(arguments[0]);

  if (arguments.length > 1)
  {
    var justArgs = new Array();
    for (var i = 1; i < arguments.length; ++i)
    {
      justArgs.push(arguments[i]);
    }
    qs += ('&' + this.flashSerializer.serialize(justArgs));
  }

  var divName = '_flash_proxy_' + this.uid;
  if(!document.getElementById(divName))
  {
    var newTarget = document.createElement("div");
    newTarget.id = divName;
    document.body.appendChild(newTarget);
  }
  var target = document.getElementById(divName);
  var ft = new FlashTag(this.proxySwfName, 1, 1);
  ft.setVersion('6,0,65,0');
  ft.setFlashvars(qs);
  target.innerHTML = ft.toString();
}

/**
 * This is the function that proxies function calls from Flash to JavaScript.
 * It is called implicitly.
 */
FlashProxy.callJS = function()
{
  var functionToCall = eval(arguments[0]);
  var argArray = new Array();
  for (var i = 1; i < arguments.length; ++i)
  {
    argArray.push(arguments[i]);
  }
  functionToCall.apply(functionToCall, argArray);
}

/*
 * jQuery corner plugin
 *
 * version 1.91 (9/21/2007)
 *
 * Dual licensed under the MIT and GPL licenses:
 *  http://www.opensource.org/licenses/mit-license.php
 *  http://www.gnu.org/licenses/gpl.html
 */

/**
 * The corner() method provides a simple way of styling DOM elements. 
 *
 * corner() takes a single string argument: jQuery().corner("effect corners width")
 *
 *  effect: The name of the effect to apply, such as round or bevel. 
 *      If you don't specify an effect, rounding is used.
 *
 *  corners: The corners can be one or more of top, bottom, tr, tl, br, or bl. 
 *      By default, all four corners are adorned. 
 *
 *  width:  The width specifies the width of the effect; in the case of rounded corners this 
 *      will be the radius of the width. 
 *      Specify this value using the px suffix such as 10px, and yes it must be pixels.
 *
 * For more details see: http://methvin.com/jquery/jq-corner.html
 * For a full demo see: http://malsup.com/jquery/corner/
 *
 *
 * @example jQuery('.adorn').corner();
 * @desc Create round, 10px corners 
 *
 * @example jQuery('.adorn').corner("25px");
 * @desc Create round, 25px corners 
 *
 * @example jQuery('.adorn').corner("notch bottom");
 * @desc Create notched, 10px corners on bottom only
 *
 * @example jQuery('.adorn').corner("tr dog 25px");
 * @desc Create dogeared, 25px corner on the top-right corner only
 *
 * @example jQuery('.adorn').corner("round 8px").parent().css('padding', '4px').corner("round 10px");
 * @desc Create a rounded border effect by styling both the element and its parent
 * 
 * @name corner
 * @type jQuery
 * @param String options Options which control the corner style
 * @cat Plugins/Corner
 * @return jQuery
 * @author Dave Methvin (dave.methvin@gmail.com)
 * @author Mike Alsup (malsup@gmail.com)
 */


jQuery.fn.corner = function(o) {
  function hex2(s) {
    var s = parseInt(s).toString(16);
    return ( s.length < 2 ) ? '0'+s : s;
  };
  function gpc(node) {
    for ( ; node && node.nodeName.toLowerCase() != 'html'; node = node.parentNode ) {
      var v = jQuery.css(node,'backgroundColor');
      if ( v.indexOf('rgb') >= 0 ) { 
        if (jQuery.browser.safari && v == 'rgba(0, 0, 0, 0)')
          continue;
        var rgb = v.match(/\d+/g); 
        return '#'+ hex2(rgb[0]) + hex2(rgb[1]) + hex2(rgb[2]);
      }
      if ( v && v != 'transparent' )
        return v;
    }
    return '#ffffff';
  };
  function getW(i) {
    switch(fx) {
    case 'round': return Math.round(width*(1-Math.cos(Math.asin(i/width))));
    case 'cool':  return Math.round(width*(1+Math.cos(Math.asin(i/width))));
    case 'sharp': return Math.round(width*(1-Math.cos(Math.acos(i/width))));
    case 'bite':  return Math.round(width*(Math.cos(Math.asin((width-i-1)/width))));
    case 'slide': return Math.round(width*(Math.atan2(i,width/i)));
    case 'jut':  return Math.round(width*(Math.atan2(width,(width-i-1))));
    case 'curl':  return Math.round(width*(Math.atan(i)));
    case 'tear':  return Math.round(width*(Math.cos(i)));
    case 'wicked': return Math.round(width*(Math.tan(i)));
    case 'long':  return Math.round(width*(Math.sqrt(i)));
    case 'sculpt': return Math.round(width*(Math.log((width-i-1),width)));
    case 'dog':  return (i&1) ? (i+1) : width;
    case 'dog2':  return (i&2) ? (i+1) : width;
    case 'dog3':  return (i&3) ? (i+1) : width;
    case 'fray':  return (i%2)*width;
    case 'notch': return width; 
    case 'bevel': return i+1;
    }
  };
  o = (o||"").toLowerCase();
  var keep = /keep/.test(o);            // keep borders?
  var cc = ((o.match(/cc:(#[0-9a-f]+)/)||[])[1]); // corner color
  var sc = ((o.match(/sc:(#[0-9a-f]+)/)||[])[1]); // strip color
  var width = parseInt((o.match(/(\d+)px/)||[])[1]) || 10; // corner width
  var re = /round|bevel|notch|bite|cool|sharp|slide|jut|curl|tear|fray|wicked|sculpt|long|dog3|dog2|dog/;
  var fx = ((o.match(re)||['round'])[0]);
  var edges = { T:0, B:1 };
  var opts = {
    TL: /top|tl/.test(o),    TR: /top|tr/.test(o),
    BL: /bottom|bl/.test(o),  BR: /bottom|br/.test(o)
  };
  if ( !opts.TL && !opts.TR && !opts.BL && !opts.BR )
    opts = { TL:1, TR:1, BL:1, BR:1 };
  var strip = document.createElement('div');
  strip.style.overflow = 'hidden';
  strip.style.height = '1px';
  strip.style.backgroundColor = sc || 'transparent';
  strip.style.borderStyle = 'solid';
  return this.each(function(index){
    var pad = {
      T: parseInt(jQuery.css(this,'paddingTop'))||0,   R: parseInt(jQuery.css(this,'paddingRight'))||0,
      B: parseInt(jQuery.css(this,'paddingBottom'))||0, L: parseInt(jQuery.css(this,'paddingLeft'))||0
    };

    if (jQuery.browser.msie) this.style.zoom = 1; // force 'hasLayout' in IE
    if (!keep) this.style.border = 'none';
    strip.style.borderColor = cc || gpc(this.parentNode);
    var cssHeight = jQuery.curCSS(this, 'height');

    for (var j in edges) {
      var bot = edges[j];
      // only add stips if needed
      if ((bot && (opts.BL || opts.BR)) || (!bot && (opts.TL || opts.TR))) {
        strip.style.borderStyle = 'none '+(opts[j+'R']?'solid':'none')+' none '+(opts[j+'L']?'solid':'none');
        var d = document.createElement('div');
        jQuery(d).addClass('jquery-corner');
        var ds = d.style;

        bot ? this.appendChild(d) : this.insertBefore(d, this.firstChild);

        if (bot && cssHeight != 'auto') {
          if (jQuery.css(this,'position') == 'static')
            this.style.position = 'relative';
          ds.position = 'absolute';
          ds.bottom = ds.left = ds.padding = ds.margin = '0';
          if (jQuery.browser.msie)
            ds.setExpression('width', 'this.parentNode.offsetWidth');
          else
            ds.width = '100%';
        }
        else {
          ds.margin = !bot ? '-'+pad.T+'px -'+pad.R+'px '+(pad.T-width)+'px -'+pad.L+'px' : 
                    (pad.B-width)+'px -'+pad.R+'px -'+pad.B+'px -'+pad.L+'px';        
        }

        for (var i=0; i < width; i++) {
          var w = Math.max(0,getW(i));
          var e = strip.cloneNode(false);
          e.style.borderWidth = '0 '+(opts[j+'R']?w:0)+'px 0 '+(opts[j+'L']?w:0)+'px';
          bot ? d.appendChild(e) : d.insertBefore(e, d.firstChild);
        }
      }
    }
  });
};

jQuery.fn.uncorner = function(o) { return jQuery('.jquery-corner', this).remove(); };
  

/*
 * jQuery Cycle Plugin for light-weight slideshows
 * Examples and documentation at: http://malsup.com/jquery/cycle/
 * Copyright (c) 2007 M. Alsup
 * Version: 1.96 (9/30/2007)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 * Requires: jQuery v1.1.3.1 or later
 *
 * Based on the work of:
 * 1) Matt Oakes (http://portfolio.gizone.co.uk/applications/slideshow/)
 * 2) Torsten Baldes (http://medienfreunde.com/lab/innerfade/)
 * 3) Benjamin Sterling (http://www.benjaminsterling.com/experiments/jqShuffle/)
 */
(function(jQuery) {

var ver = '1.96';

jQuery.fn.cycle = function(options) {
  return this.each(function() {
    if (options && options.constructor == String) {
      switch(options) {
      case 'stop':
        if (this.cycleTimeout) clearTimeout(this.cycleTimeout);
        this.cycleTimeout = 0;
        return;
      case 'pause':
        this.cyclePause = 1;
        return;
      case 'resume':
        this.cyclePause = 0;
        return;
      default:
        options = { fx: options };
      };
    }
    var jQuerycont = jQuery(this), jQueryslides = jQuerycont.children(), els = jQueryslides.get();
    if (els.length < 2) return; // don't bother

    var opts = jQuery.extend({}, jQuery.fn.cycle.defaults, options || {}, jQuery.meta ? jQuerycont.data() : {});
    if (opts.autostop) 
      opts.countdown = opts.autostopCount || els.length;
      
    opts.before = opts.before ? [opts.before] : [];
    opts.after = opts.after ? [opts.after] : [];
    opts.after.unshift(function(){ opts.busy=0; });

    // allow shorthand overrides of width, height and timeout
    var cls = this.className;
    var w = parseInt((cls.match(/w:(\d+)/)||[])[1]) || opts.width;
    var h = parseInt((cls.match(/h:(\d+)/)||[])[1]) || opts.height;
    opts.timeout = parseInt((cls.match(/t:(\d+)/)||[])[1]) || opts.timeout;

    if (jQuerycont.css('position') == 'static') 
      jQuerycont.css('position', 'relative');
    if (w) 
      jQuerycont.width(w);
    if (h && h != 'auto') 
      jQuerycont.height(h);

    jQueryslides.each(function(i){ jQuery(this).css('z-index', els.length-i) }).css('position','absolute').hide();
    jQuery(els[0]).show();
    if (opts.fit && w) 
      jQueryslides.width(w);
    if (opts.fit && h && h != 'auto') 
      jQueryslides.height(h);
    if (opts.pause) 
      jQuerycont.hover(function(){this.cyclePause=1;}, function(){this.cyclePause=0;});

    // run transition init fn
    var init = jQuery.fn.cycle.transitions[opts.fx];
    if (jQuery.isFunction(init))
      init(jQuerycont, jQueryslides, opts);

    jQueryslides.each(function() {
      var jQueryel = jQuery(this);
      this.cycleH = (opts.fit && h) ? h : jQueryel.height();
      this.cycleW = (opts.fit && w) ? w : jQueryel.width();
    });

    opts.cssBefore = opts.cssBefore || {};
    opts.animIn = opts.animIn || {};
    opts.animOut = opts.animOut || {};

    jQueryslides.not(':eq(0)').css(opts.cssBefore);
    if (opts.cssFirst)
      jQuery(jQueryslides[0]).css(opts.cssFirst);

    if (opts.timeout) {
      // ensure that timeout and speed settings are sane
      if (opts.speed.constructor == String)
        opts.speed = {slow: 600, fast: 200}[opts.speed] || 400;
      if (!opts.sync)
        opts.speed = opts.speed / 2;
      while((opts.timeout - opts.speed) < 250)
        opts.timeout += opts.speed;
    }
    if (opts.easing) 
      opts.easeIn = opts.easeOut = opts.easing;
    if (!opts.speedIn) 
      opts.speedIn = opts.speed;
    if (!opts.speedOut) 
      opts.speedOut = opts.speed;

    opts.nextSlide = opts.random ? (Math.floor(Math.random() * (els.length-1)))+1 : 1;
    opts.currSlide = 0;

    // fire artificial events
    var e0 = jQueryslides[0];
    if (opts.before.length)
      opts.before[0].apply(e0, [e0, e0, opts, true]);
    if (opts.after.length > 1)
      opts.after[1].apply(e0, [e0, e0, opts, true]);
    
    if (opts.click && !opts.next)
      opts.next = opts.click;
    if (opts.next)
      jQuery(opts.next).bind('click', function(){return advance(els,opts,opts.rev?-1:1)});
    if (opts.prev)
      jQuery(opts.prev).bind('click', function(){return advance(els,opts,opts.rev?1:-1)});
    if (opts.pager)
      buildPager(els,opts);
    if (opts.timeout)
      this.cycleTimeout = setTimeout(function(){go(els,opts,0,!opts.rev)}, opts.timeout + (opts.delay||0));
  });
};

function go(els, opts, manual, fwd) {
  if (opts.busy) return;

  var p = els[0].parentNode, curr = els[opts.currSlide], next = els[opts.nextSlide];
  if (p.cycleTimeout === 0 && !manual) 
    return;

  if (!manual && !p.cyclePause && opts.autostop && (--opts.countdown <= 0)) 
    return;

  if (manual || !p.cyclePause) {
    if (opts.before.length)
      jQuery.each(opts.before, function(i,o) { o.apply(next, [curr, next, opts, fwd]); });
    var after = function() {
      jQuery.each(opts.after, function(i,o) { o.apply(next, [curr, next, opts, fwd]); });
    };

    if (opts.nextSlide != opts.currSlide) {
      opts.busy = 1;
      if (opts.fxFn)
        opts.fxFn(curr, next, opts, after);
      else if (jQuery.isFunction(jQuery.fn.cycle[opts.fx]))
        jQuery.fn.cycle[opts.fx](curr, next, opts, after);
      else
        jQuery.fn.cycle.custom(curr, next, opts, after);
    }
    if (opts.random) {
      opts.currSlide = opts.nextSlide;
      while (opts.nextSlide == opts.currSlide)
        opts.nextSlide = Math.floor(Math.random() * els.length);
    }
    else { // sequence
      var roll = (opts.nextSlide + 1) == els.length;
      opts.nextSlide = roll ? 0 : opts.nextSlide+1;
      opts.currSlide = roll ? els.length-1 : opts.nextSlide-1;
    }
    if (opts.pager)
      jQuery(opts.pager).find('a').removeClass('activeSlide').filter('a:eq('+opts.currSlide+')').addClass('activeSlide');
  }
  if (opts.timeout)
    p.cycleTimeout = setTimeout(function() { go(els,opts,0,!opts.rev) }, opts.timeout);
};

// advance slide forward or back
function advance(els, opts, val) {
  var p = els[0].parentNode, timeout = p.cycleTimeout;
  if (timeout) {
    clearTimeout(timeout);
    p.cycleTimeout = 0;
  }
  opts.nextSlide = opts.currSlide + val;
  if (opts.nextSlide < 0)
    opts.nextSlide = els.length - 1;
  else if (opts.nextSlide >= els.length)
    opts.nextSlide = 0;
  go(els, opts, 1, val>=0);
  return false;
};

function buildPager(els, opts) {
  var jQueryp = jQuery(opts.pager);
  jQuery.each(els, function(i,o) {
    var jQuerya = jQuery('<a href="#">'+(i+1)+'</a>').appendTo(jQueryp).bind('click',function() {
      opts.nextSlide = i;
      var p = els[0].parentNode, timeout = p.cycleTimeout;
        if (timeout) {
          clearTimeout(timeout);
          p.cycleTimeout = 0;
        }      
      go(els,opts,1,!opts.rev);
      return false;
    });
    if (i == 0) 
      jQuerya.addClass('activeSlide');
  });
};

jQuery.fn.cycle.custom = function(curr, next, opts, cb) {
  var jQueryl = jQuery(curr), jQueryn = jQuery(next);
  jQueryn.css(opts.cssBefore);
  var fn = function() {jQueryn.animate(opts.animIn, opts.speedIn, opts.easeIn, cb)};
  jQueryl.animate(opts.animOut, opts.speedOut, opts.easeOut, function() {
    if (opts.cssAfter) jQueryl.css(opts.cssAfter);
    if (!opts.sync) fn();
  });
  if (opts.sync) fn();
};

jQuery.fn.cycle.transitions = {
  fade: function(jQuerycont, jQueryslides, opts) {
    jQueryslides.not(':eq(0)').css('opacity',0);
    opts.before.push(function() { jQuery(this).show() });
    opts.animIn  = { opacity: 1 };
    opts.animOut  = { opacity: 0 };
    opts.cssAfter = { display: 'none' };
  }
};

jQuery.fn.cycle.ver = function() { return ver; };

// override these globally if you like (they are all optional)
jQuery.fn.cycle.defaults = {
  fx:     'fade', // one of: fade, shuffle, zoom, slideX, slideY, scrollUp/Down/Left/Right
  timeout:   4000, // milliseconds between slide transitions (0 to disable auto advance)
  speed:    1000, // speed of the transition (any valid fx speed value)
  speedIn:   null, // speed of the 'in' transition
  speedOut:  null, // speed of the 'out' transition
  click:    null, // @deprecated; please use the 'next' option
  next:    null, // id of element to use as click trigger for next slide
  prev:    null, // id of element to use as click trigger for previous slide
  pager:    null, // id of element to use as pager container
  before:   null, // transition callback (scope set to element to be shown)
  after:    null, // transition callback (scope set to element that was shown)
  easing:   null, // easing method for both in and out transitions
  easeIn:   null, // easing for "in" transition
  easeOut:   null, // easing for "out" transition
  shuffle:   null, // coords for shuffle animation, ex: { top:15, left: 200 }
  animIn:   null, // properties that define how the slide animates in
  animOut:   null, // properties that define how the slide animates out
  cssBefore:  null, // properties that define the initial state of the slide before transitioning in
  cssAfter:  null, // properties that defined the state of the slide after transitioning out
  fxFn:    null, // function used to control the transition
  height:   'auto', // container height
  sync:    1,   // true if in/out transitions should occur simultaneously
  random:   0,   // true for random, false for sequence (not applicable to shuffle fx)
  fit:     0,   // force slides to fit container
  pause:    0,   // true to enable "pause on hover"
  autostop:  0,   // true to end slideshow after X transitions (where X == slide count)
  delay:    0   // additional delay (in ms) for first transition (hint: can be negative)
};

})(jQuery);

/*
 * jQuery Cycle Plugin Transition Definitions
 * This script is a plugin for the jQuery Cycle Plugin
 * Examples and documentation at: http://malsup.com/jquery/cycle/
 * Copyright (c) 2007 M. Alsup
 * Version: 1.93
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 */

//
// These functions define one-time slide initialization for the named
// transitions. To save file size feel free to remove any of these that you 
// don't need.
//

// scrollUp/Down/Left/Right
jQuery.fn.cycle.transitions.scrollUp = function(jQuerycont, jQueryslides, opts) {
  jQuerycont.css('overflow','hidden');
  opts.before.push(function(curr, next, opts) {
    jQuery(this).show();
    opts.cssBefore.top = next.offsetHeight;
    opts.animOut.top = 0-curr.offsetHeight;
  });
  opts.cssFirst = { top: 0 };
  opts.animIn  = { top: 0 };
  opts.cssAfter = { display: 'none' };
};
jQuery.fn.cycle.transitions.scrollDown = function(jQuerycont, jQueryslides, opts) {
  jQuerycont.css('overflow','hidden');
  opts.before.push(function(curr, next, opts) {
    jQuery(this).show();
    opts.cssBefore.top = 0-next.offsetHeight;
    opts.animOut.top = curr.offsetHeight;
  });
  opts.cssFirst = { top: 0 };
  opts.animIn  = { top: 0 };
  opts.cssAfter = { display: 'none' };
};
jQuery.fn.cycle.transitions.scrollLeft = function(jQuerycont, jQueryslides, opts) {
  jQuerycont.css('overflow','hidden');
  opts.before.push(function(curr, next, opts) {
    jQuery(this).show();
    opts.cssBefore.left = next.offsetWidth;
    opts.animOut.left = 0-curr.offsetWidth;
  });
  opts.cssFirst = { left: 0 };
  opts.animIn  = { left: 0 };
};
jQuery.fn.cycle.transitions.scrollRight = function(jQuerycont, jQueryslides, opts) {
  jQuerycont.css('overflow','hidden');
  opts.before.push(function(curr, next, opts) {
    jQuery(this).show();
    opts.cssBefore.left = 0-next.offsetWidth;
    opts.animOut.left = curr.offsetWidth;
  });
  opts.cssFirst = { left: 0 };
  opts.animIn  = { left: 0 };
};
jQuery.fn.cycle.transitions.scrollHorz = function(jQuerycont, jQueryslides, opts) {
  jQuerycont.css('overflow','hidden').width();
//  jQueryslides.show();
  opts.before.push(function(curr, next, opts, fwd) {
    jQuery(this).show();
    var currW = curr.offsetWidth, nextW = next.offsetWidth;
    opts.cssBefore = fwd ? { left: nextW } : { left: -nextW };
    opts.animIn.left = 0;
    opts.animOut.left = fwd ? -currW : currW;
    jQueryslides.not(curr).css(opts.cssBefore);
  });
  opts.cssFirst = { left: 0 };
  opts.cssAfter = { display: 'none' }
};
jQuery.fn.cycle.transitions.scrollVert = function(jQuerycont, jQueryslides, opts) {
  jQuerycont.css('overflow','hidden');
//  jQueryslides.show();
  opts.before.push(function(curr, next, opts, fwd) {
    jQuery(this).show();
    var currH = curr.offsetHeight, nextH = next.offsetHeight;
    opts.cssBefore = fwd ? { top: -nextH } : { top: nextH };
    opts.animIn.top = 0;
    opts.animOut.top = fwd ? currH : -currH;
    jQueryslides.not(curr).css(opts.cssBefore);
  });
  opts.cssFirst = { top: 0 };
  opts.cssAfter = { display: 'none' }
};

// slideX/slideY
jQuery.fn.cycle.transitions.slideX = function(jQuerycont, jQueryslides, opts) {
  opts.animIn = { width: 'show' };
  opts.animOut = { width: 'hide' };
};
jQuery.fn.cycle.transitions.slideY = function(jQuerycont, jQueryslides, opts) {
  opts.animIn = { height: 'show' };
  opts.animOut = { height: 'hide' };
};

// shuffle
jQuery.fn.cycle.transitions.shuffle = function(jQuerycont, jQueryslides, opts) {
  var w = jQuerycont.css('overflow', 'visible').width();
  jQueryslides.css({left: 0, top: 0});
  opts.before.push(function() { jQuery(this).show() });
  opts.speed = opts.speed / 2; // shuffle has 2 transitions    
  opts.random = 0;
  opts.shuffle = opts.shuffle || {left:-w, top:15};
  opts.els = [];
  for (var i=0; i < jQueryslides.length; i++)
    opts.els.push(jQueryslides[i]);

  // custom transition fn (hat tip to Benjamin Sterling for this bit of sweetness!)
  opts.fxFn = function(curr, next, opts, cb) {
    var jQueryel = jQuery(curr);
    jQueryel.animate(opts.shuffle, opts.speedIn, opts.easeIn, function() {
      opts.els.push(opts.els.shift());
      for (var i=0, len=opts.els.length; i < len; i++)
        jQuery(opts.els[i]).css('z-index', len-i);
      jQueryel.animate({left:0, top:0}, opts.speedOut, opts.easeOut, function() {
        jQuery(this).hide();
        if (cb) cb();
      });
    });
  };
};

// turnUp/Down/Left/Right
jQuery.fn.cycle.transitions.turnUp = function(jQuerycont, jQueryslides, opts) {
  opts.before.push(function(curr, next, opts) {
    jQuery(this).show();
    opts.cssBefore.top = next.cycleH;
    opts.animIn.height = next.cycleH;
  });
  opts.cssFirst = { top: 0 };
  opts.cssBefore = { height: 0 };
  opts.animIn  = { top: 0 };
  opts.animOut  = { height: 0 };
  opts.cssAfter = { display: 'none' };
};
jQuery.fn.cycle.transitions.turnDown = function(jQuerycont, jQueryslides, opts) {
  opts.before.push(function(curr, next, opts) {
    jQuery(this).show();
    opts.animIn.height = next.cycleH;
    opts.animOut.top  = curr.cycleH;
  });
  opts.cssFirst = { top: 0 };
  opts.cssBefore = { top: 0, height: 0 };
  opts.animOut  = { height: 0 };
  opts.cssAfter = { display: 'none' };
};
jQuery.fn.cycle.transitions.turnLeft = function(jQuerycont, jQueryslides, opts) {
  opts.before.push(function(curr, next, opts) {
    jQuery(this).show();
    opts.cssBefore.left = next.cycleW;
    opts.animIn.width = next.cycleW;
  });
  opts.cssBefore = { width: 0 };
  opts.animIn  = { left: 0 };
  opts.animOut  = { width: 0 };
  opts.cssAfter = { display: 'none' };
};
jQuery.fn.cycle.transitions.turnRight = function(jQuerycont, jQueryslides, opts) {
  opts.before.push(function(curr, next, opts) {
    jQuery(this).show();
    opts.animIn.width = next.cycleW;
    opts.animOut.left = curr.cycleW;
  });
  opts.cssBefore = { left: 0, width: 0 };
  opts.animIn  = { left: 0 };
  opts.animOut  = { width: 0 };
  opts.cssAfter = { display: 'none' };
};

// zoom
jQuery.fn.cycle.transitions.zoom = function(jQuerycont, jQueryslides, opts) {
  opts.cssFirst = { top:0, left: 0 }; 
  opts.cssAfter = { display: 'none' };
  
  opts.before.push(function(curr, next, opts) {
    jQuery(this).show();
    opts.cssBefore = { width: 0, height: 0, top: next.cycleH/2, left: next.cycleW/2 };
    opts.animIn  = { top: 0, left: 0, width: next.cycleW, height: next.cycleH };
    opts.animOut  = { width: 0, height: 0, top: curr.cycleH/2, left: curr.cycleW/2 };
  });  
};
/* Copyright (c) 2006 Brandon Aaron (http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * $LastChangedDate: 2007-02-18 22:09:54 -0600 (Sun, 18 Feb 2007) $
 * $Rev: 1379 $
 */

/**
 * The bgiframe is chainable and applies the iframe hack to get 
 * around zIndex issues in IE6. It will only apply itself in IE 
 * and adds a class to the iframe called 'bgiframe'.
 * 
 * It does take borders into consideration but all values
 * need to be in pixels and the element needs to have
 * position relative or absolute.
 *
 * NOTICE: This plugin uses CSS expersions in order to work
 * with an element's borders, height and with and can result in poor 
 * performance when used on an element that changes properties 
 * like size and position a lot. Two of these expressions can be
 * removed if border doesn't matter and performance does.
 * See lines 39 and 40 below and set top: 0 and left: 0
 * instead of their current values.
 *
 * @example $('div').bgiframe();
 * @before <div><p>Paragraph</p></div>
 * @result <div><iframe class="bgiframe".../><p>Paragraph</p></div>
 *
 * @name bgiframe
 * @type jQuery
 * @cat Plugins/bgiframe
 * @author Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 */
jQuery.fn.bgIframe = jQuery.fn.bgiframe = function() {
	// This is only for IE6
	if ( !(jQuery.browser.msie && typeof XMLHttpRequest == 'function') ) return this;
	var html = '<iframe class="bgiframe" src="javascript:false;document.write(\'\');" tabindex="-1" '
	 					+'style="display:block; position:absolute; '
						+'top: expression(((parseInt(this.parentNode.currentStyle.borderTopWidth) || 0) * -1) + \'px\'); '
						+'left:expression(((parseInt(this.parentNode.currentStyle.borderLeftWidth) || 0) * -1) + \'px\'); ' 
						+'z-index:-1; filter:Alpha(Opacity=\'0\'); '
						+'width:expression(this.parentNode.offsetWidth + \'px\'); '
						+'height:expression(this.parentNode.offsetHeight + \'px\')"/>';
	return this.each(function() {
		if ( !jQuery('iframe.bgiframe', this)[0] )
			this.insertBefore( document.createElement(html), this.firstChild );
	});
};/*
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * $LastChangedDate: 2007-03-04 20:15:11 -0600 (Sun, 04 Mar 2007) $
 * $Rev: 1485 $
 */

jQuery.fn._height = jQuery.fn.height;
jQuery.fn._width = jQuery.fn.width;

/**
 * If used on document, returns the document's height (innerHeight)
 * If used on window, returns the viewport's (window) height
 * See core docs on height() to see what happens when used on an element.
 *
 * @example $("#testdiv").height()
 * @result 200
 *
 * @example $(document).height()
 * @result 800
 *
 * @example $(window).height()
 * @result 400
 *
 * @name height
 * @type Object
 * @cat Plugins/Dimensions
 */
jQuery.fn.height = function() {
	if ( this[0] == window )
		return self.innerHeight ||
			jQuery.boxModel && document.documentElement.clientHeight ||
			document.body.clientHeight;

	if ( this[0] == document )
		return Math.max( document.body.scrollHeight, document.body.offsetHeight );

	return this._height(arguments[0]);
};

/**
 * If used on document, returns the document's width (innerWidth)
 * If used on window, returns the viewport's (window) width
 * See core docs on height() to see what happens when used on an element.
 *
 * @example $("#testdiv").width()
 * @result 200
 *
 * @example $(document).width()
 * @result 800
 *
 * @example $(window).width()
 * @result 400
 *
 * @name width
 * @type Object
 * @cat Plugins/Dimensions
 */
jQuery.fn.width = function() {
	if ( this[0] == window )
		return self.innerWidth ||
			jQuery.boxModel && document.documentElement.clientWidth ||
			document.body.clientWidth;

	if ( this[0] == document )
		return Math.max( document.body.scrollWidth, document.body.offsetWidth );

	return this._width(arguments[0]);
};

/**
 * Returns the inner height value (without border) for the first matched element.
 * If used on document, returns the document's height (innerHeight)
 * If used on window, returns the viewport's (window) height
 *
 * @example $("#testdiv").innerHeight()
 * @result 800
 *
 * @name innerHeight
 * @type Number
 * @cat Plugins/Dimensions
 */
jQuery.fn.innerHeight = function() {
	return this[0] == window || this[0] == document ?
		this.height() :
		this.css('display') != 'none' ?
		 	this[0].offsetHeight - (parseInt(this.css("borderTopWidth")) || 0) - (parseInt(this.css("borderBottomWidth")) || 0) :
			this.height() + (parseInt(this.css("paddingTop")) || 0) + (parseInt(this.css("paddingBottom")) || 0);
};

/**
 * Returns the inner width value (without border) for the first matched element.
 * If used on document, returns the document's Width (innerWidth)
 * If used on window, returns the viewport's (window) width
 *
 * @example $("#testdiv").innerWidth()
 * @result 1000
 *
 * @name innerWidth
 * @type Number
 * @cat Plugins/Dimensions
 */
jQuery.fn.innerWidth = function() {
	return this[0] == window || this[0] == document ?
		this.width() :
		this.css('display') != 'none' ?
			this[0].offsetWidth - (parseInt(this.css("borderLeftWidth")) || 0) - (parseInt(this.css("borderRightWidth")) || 0) :
			this.height() + (parseInt(this.css("paddingLeft")) || 0) + (parseInt(this.css("paddingRight")) || 0);
};

/**
 * Returns the outer height value (including border) for the first matched element.
 * Cannot be used on document or window.
 *
 * @example $("#testdiv").outerHeight()
 * @result 1000
 *
 * @name outerHeight
 * @type Number
 * @cat Plugins/Dimensions
 */
jQuery.fn.outerHeight = function() {
	return this[0] == window || this[0] == document ?
		this.height() :
		this.css('display') != 'none' ?
			this[0].offsetHeight :
			this.height() + (parseInt(this.css("borderTopWidth")) || 0) + (parseInt(this.css("borderBottomWidth")) || 0)
				+ (parseInt(this.css("paddingTop")) || 0) + (parseInt(this.css("paddingBottom")) || 0);
};

/**
 * Returns the outer width value (including border) for the first matched element.
 * Cannot be used on document or window.
 *
 * @example $("#testdiv").outerWidth()
 * @result 1000
 *
 * @name outerWidth
 * @type Number
 * @cat Plugins/Dimensions
 */
jQuery.fn.outerWidth = function() {
	return this[0] == window || this[0] == document ?
		this.width() :
		this.css('display') != 'none' ?
			this[0].offsetWidth :
			this.height() + (parseInt(this.css("borderLeftWidth")) || 0) + (parseInt(this.css("borderRightWidth")) || 0)
				+ (parseInt(this.css("paddingLeft")) || 0) + (parseInt(this.css("paddingRight")) || 0);
};

/**
 * Returns how many pixels the user has scrolled to the right (scrollLeft).
 * Works on containers with overflow: auto and window/document.
 *
 * @example $("#testdiv").scrollLeft()
 * @result 100
 *
 * @name scrollLeft
 * @type Number
 * @cat Plugins/Dimensions
 */
jQuery.fn.scrollLeft = function() {
	if ( this[0] == window || this[0] == document )
		return self.pageXOffset ||
			jQuery.boxModel && document.documentElement.scrollLeft ||
			document.body.scrollLeft;

	return this[0].scrollLeft;
};

/**
 * Returns how many pixels the user has scrolled to the bottom (scrollTop).
 * Works on containers with overflow: auto and window/document.
 *
 * @example $("#testdiv").scrollTop()
 * @result 100
 *
 * @name scrollTop
 * @type Number
 * @cat Plugins/Dimensions
 */
jQuery.fn.scrollTop = function() {
	if ( this[0] == window || this[0] == document )
		return self.pageYOffset ||
			jQuery.boxModel && document.documentElement.scrollTop ||
			document.body.scrollTop;

	return this[0].scrollTop;
};

/**
 * Returns the location of the element in pixels from the top left corner of the viewport.
 *
 * For accurate readings make sure to use pixel values for margins, borders and padding.
 *
 * @example $("#testdiv").offset()
 * @result { top: 100, left: 100, scrollTop: 10, scrollLeft: 10 }
 *
 * @example $("#testdiv").offset({ scroll: false })
 * @result { top: 90, left: 90 }
 *
 * @example var offset = {}
 * $("#testdiv").offset({ scroll: false }, offset)
 * @result offset = { top: 90, left: 90 }
 *
 * @name offset
 * @param Object options A hash of options describing what should be included in the final calculations of the offset.
 *            The options include:
 *              margin: Should the margin of the element be included in the calculations? True by default.
 *                  If set to false the margin of the element is subtracted from the total offset.
 *              border: Should the border of the element be included in the calculations? True by default.
 *                  If set to false the border of the element is subtracted from the total offset.
 *              padding: Should the padding of the element be included in the calculations? False by default.
 *                  If set to true the padding of the element is added to the total offset.
 *              scroll: Should the scroll offsets of the parent elements be included in the calculations?
 *                  True by default. When true, it adds the total scroll offsets of all parents to the
 *                  total offset and also adds two properties to the returned object, scrollTop and
 *                  scrollLeft. If set to false the scroll offsets of parent elements are ignored.
 *                  If scroll offsets are not needed, set to false to get a performance boost.
 * @param Object returnObject An object to store the return value in, so as not to break the chain. If passed in the
 *              chain will not be broken and the result will be assigned to this object.
 * @type Object
 * @cat Plugins/Dimensions
 * @author Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 */
jQuery.fn.offset = function(options, returnObject) {
	var x = 0, y = 0, elem = this[0], parent = this[0], op, sl = 0, st = 0, options = jQuery.extend({ margin: true, border: true, padding: false, scroll: true }, options || {});
	do {
		x += parent.offsetLeft || 0;
		y += parent.offsetTop || 0;

		// Mozilla and IE do not add the border
		if (jQuery.browser.mozilla || jQuery.browser.msie) {
			// get borders
			var bt = parseInt(jQuery.css(parent, 'borderTopWidth')) || 0;
			var bl = parseInt(jQuery.css(parent, 'borderLeftWidth')) || 0;

			// add borders to offset
			x += bl;
			y += bt;

			// Mozilla removes the border if the parent has overflow property other than visible
			if (jQuery.browser.mozilla && parent != elem && jQuery.css(parent, 'overflow') != 'visible') {
				x += bl;
				y += bt;
			}
		}

		if (options.scroll) {
			// Need to get scroll offsets in-between offsetParents
			op = parent.offsetParent;
			do {
				sl += parent.scrollLeft || 0;
				st += parent.scrollTop || 0;

				parent = parent.parentNode;

				// Mozilla removes the border if the parent has overflow property other than visible
				if (jQuery.browser.mozilla && parent != elem && parent != op && jQuery.css(parent, 'overflow') != 'visible') {
					y += parseInt(jQuery.css(parent, 'borderTopWidth')) || 0;
					x += parseInt(jQuery.css(parent, 'borderLeftWidth')) || 0;
				}
			} while (parent != op);
		} else
			parent = parent.offsetParent;

		if (parent && (parent.tagName.toLowerCase() == 'body' || parent.tagName.toLowerCase() == 'html')) {
			// Safari doesn't add the body margin for elments positioned with static or relative
			if ((jQuery.browser.safari || (jQuery.browser.msie && jQuery.boxModel)) && jQuery.css(parent, 'position') != 'absolute') {
				x += parseInt(jQuery.css(op, 'marginLeft')) || 0;
				y += parseInt(jQuery.css(op, 'marginTop')) || 0;
			}
			break; // Exit the loop
		}
	} while (parent);

	if ( !options.margin) {
		x -= parseInt(jQuery.css(elem, 'marginLeft')) || 0;
		y -= parseInt(jQuery.css(elem, 'marginTop')) || 0;
	}

	// Safari and Opera do not add the border for the element
	if ( options.border && (jQuery.browser.safari || jQuery.browser.opera) ) {
		x += parseInt(jQuery.css(elem, 'borderLeftWidth')) || 0;
		y += parseInt(jQuery.css(elem, 'borderTopWidth')) || 0;
	} else if ( !options.border && !(jQuery.browser.safari || jQuery.browser.opera) ) {
		x -= parseInt(jQuery.css(elem, 'borderLeftWidth')) || 0;
		y -= parseInt(jQuery.css(elem, 'borderTopWidth')) || 0;
	}

	if ( options.padding ) {
		x += parseInt(jQuery.css(elem, 'paddingLeft')) || 0;
		y += parseInt(jQuery.css(elem, 'paddingTop')) || 0;
	}

	// Opera thinks offset is scroll offset for display: inline elements
	if (options.scroll && jQuery.browser.opera && jQuery.css(elem, 'display') == 'inline') {
		sl -= elem.scrollLeft || 0;
		st -= elem.scrollTop || 0;
	}

	var returnValue = options.scroll ? { top: y - st, left: x - sl, scrollTop: st, scrollLeft: sl }
	                 : { top: y, left: x };

	if (returnObject) { jQuery.extend(returnObject, returnValue); return this; }
	else       { return returnValue; }
};/*
 * jdMenu 1.3.beta2 (2007-03-06)
 *
 * Copyright (c) 2006,2007 Jonathan Sharp (http://jdsharp.us)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://jdsharp.us/
 *
 * Built upon jQuery 1.1.1 (http://jquery.com)
 * This also requires the jQuery dimensions plugin
 */
(function($){
	// This will store an element list of all our menu objects
	var jdMenu = [];
	
	// Public methods
	jQuery.fn.jdMenu = function(inSettings) {
		var settings = jQuery.extend({}, arguments.callee.defaults, inSettings);
		return this.each(function() {
			jdMenu.push(this);
			jQuery(this).addClass('jd_menu_flag_root');
			this.$settings = jQuery.extend({}, settings, {isVerticalMenu: jQuery(this).is('.jd_menu_vertical')});
			addEvents(this);
		});
	};
	jQuery.fn.jdMenuShow = function() {
		return this.each(function() {
			showMenuLI.apply(this);
		});
	};
	jQuery.fn.jdMenuHide = function() {
		return this.each(function() {
			hideMenuUL.apply(this);
		});
	};

	// Private methods and logic
	jQuery(window)
		// Bind a click event to hide all visible menus when the document is clicked
		.bind('click', function(){
			jQuery(jdMenu).find('ul:visible').jdMenuHide();
		})
		// Cleanup after ourself by nulling the $settings object
		.bind('unload', function() {
			jQuery(jdMenu).each(function() {
				this.$settings = null;
			});
		});

	// These are our default settings for this plugin
	$.fn.jdMenu.defaults = {
		activateDelay: 750,
		showDelay: 150,
		hideDelay: 550,
		onShow: null,
		onHideCheck: null,
		onHide: null,
		onAnimate: null,
		onClick: null,
		offsetX: 4,
		offsetY: 2,
		iframe: $.browser.msie
	};
	
	// Our special parentsUntil method to get all parents up to and including the matched element
	$.fn.parentsUntil = function(match) {
		var a = [];
		jQuery(this[0]).parents().each(function() {
			a.push(this);
			return !jQuery(this).is(match);
		});
		return this.pushStack(a, arguments);
	};

	// Returns our settings object for this menu
	function getSettings(el) {
		if(jQuery(el).parents('ul.jd_menu_flag_root')[0] != undefined){
			return jQuery(el).parents('ul.jd_menu_flag_root')[0].$settings;	
		}
		
	}

	// Unbind any events and then rebind them
	function addEvents(ul) {
		removeEvents(ul);
		jQuery('> li', ul)
			.hover(hoverOverLI, hoverOutLI)
			.bind('click', itemClick)
			.find('> a.accessible')
				.bind('click', accessibleClick);
	};
	
	// Remove all events for this menu
	function removeEvents(ul) {
		jQuery('> li', ul)
			.unbind('mouseover').unbind('mouseout')
			.unbind('click')
			.find('> a.accessible')
				.unbind('click');
	};
	
	function hoverOverLI() {
		var cls = 'jd_menu_hover' + (jQuery(this).parent().is('.jd_menu_flag_root') ? '_menubar' : '');
		jQuery(this).addClass(cls).find('> a').addClass(cls);
		
		if (this.$timer) {
			clearTimeout(this.$timer);
		}

		// Do we have a sub menu?
		if (jQuery('> ul', this).size() > 0) {
			var settings = getSettings(this);
			
			// Which delay to use, the longer activate one or the shorter show delay if a menu is already visible
			var delay = (jQuery(this).parents('ul.jd_menu_flag_root').find('ul:visible').size() == 0) 
							? settings.activateDelay : settings.showDelay;
			var t = this;
			this.$timer = setTimeout(function() {
				showMenuLI.apply(t);
			}, delay);
		}
	};
	
	function hoverOutLI() {
		// Remove both classes so we do not have to test which one we are
		jQuery(this)	.removeClass('jd_menu_hover').removeClass('jd_menu_hover_menubar')
			.find('> a')
				.removeClass('jd_menu_hover').removeClass('jd_menu_hover_menubar');
		
		if (this.$timer) {
			clearTimeout(this.$timer);
		}

		// TODO: Possible bug with our test for visibility in that parent menus are hidden child menus are not

		// If we have a visible menu, hide it
		if (jQuery(this).is(':visible') && jQuery('> ul', this).size() > 0) {
			var settings = getSettings(this);
			var ul = jQuery('> ul', this)[0];
			this.$timer = setTimeout(function() {
				hideMenuUL.apply(ul);
			}, settings.hideDelay);
		}
	};
	
	// "this" is a reference to the LI element that contains 
	// the UL that will be shown
	function showMenuLI() {
		var ul = jQuery('> ul', this).get(0);
		// We are already visible, just return
		if (jQuery(ul).is(':visible')) {
			return false;
		}

		// Clear our timer if it exists
		if (this.$timer) {
			clearTimeout(this.$timer);
		}

		// Get our settings object
		var settings = getSettings(this);

		// Call our callback
		if (settings.onShow != null && settings.onShow.apply(this) == false) {
			return false;
		}

		// Add hover classes, needed for accessible functionality
		var isRoot = jQuery(this).parent().is('.jd_menu_flag_root');
		var c = 'jd_menu_active' + (isRoot ? '_menubar' : '');
		jQuery(this).addClass(c).find('> a').addClass(c);

		if (!isRoot) {
			// Add the active class to the parent list item which maybe our menubar
			var c = 'jd_menu_active' + (jQuery(this).parent().parent().parent().is('.jd_menu_flag_root') ? '_menubar' : '');
			jQuery(this).parent().parent().addClass(c).find('> a').addClass(c);
		}

		// Hide any existing menues at the same level
		jQuery(this).parent().find('> li > ul:visible').not(ul).each(function() {
			hideMenuUL.apply(this);
		});

		addEvents(ul);

		// Our range object is used in calculating menu positions
		var Range = function(x1, x2, y1, y2) {
			this.x1	= x1;
			this.x2 = x2;
			this.y1 = y1;
			this.y2 = y2;
		}
		Range.prototype.contains = function(range) {
			return 	(this.x1 <= range.x1 && range.x2 <= this.x2) 
					&& 
					(this.y1 <= range.y1 && range.y2 <= this.y2);
		}
		Range.prototype.transform = function(x, y) {
			return new Range(this.x1 + x, this.x2 + x, this.y1 + y, this.y2 + y);
		}
		Range.prototype.nudgeX = function(range) {
			if (this.x1 < range.x1) {
				return new Range(range.x1, range.x1 + (this.x2 - this.x1), this.y1, this.y2);
			} else if (this.x2 > range.x2) {
				return new Range(range.x2 - (this.x2 - this.x1), range.x2, this.y1, this.y2);
			}
			return this;
		}
		Range.prototype.nudgeY = function(range) {
			if (this.y1 < range.y1) {
				return new Range(this.x1, this.x2, range.y1, range.y1 + (this.y2 - this.y1));
			} else if (this.y2 > range.y2) {
				return new Range(this.x1, this.x2, range.y2 - (this.y2 - this.y1), range.y2);
			}
			return this;
		}

		// window width & scroll offset
		var sx = jQuery(window).scrollLeft()
		var sy = jQuery(window).scrollTop();
		var ww = jQuery(window).innerWidth();
		var wh = jQuery(window).innerHeight();

		var viewport = new Range(	sx, sx + ww, 
									sy, sy + wh);

		// "Show" our menu so we can calculate its width, set left and top so that it does not accidentally
		// go offscreen and trigger browser scroll bars
		jQuery(ul).css({visibility: 'hidden', left: 0, top: 0}).show();

		var menuWidth		= jQuery(ul).outerWidth();
		var menuHeight		= jQuery(ul).outerHeight();

		// Get the LI parent UL outerwidth in case borders are applied to it
		var tp 				= jQuery(this).parent();
		var thisWidth		= tp.outerWidth();
		var thisBorderWidth	= parseInt(tp.css('borderLeftWidth')) + parseInt(tp.css('borderRightWidth'));
		//var thisBorderTop 	= parseInt(tp.css('borderTopWidth'));
		var thisHeight		= jQuery(this).outerHeight();
		var thisOffset 		= jQuery(this).offset({border: false});

		jQuery(ul).hide().css({visibility: ''});

		// We define a list of valid positions for our menu and then test against them to find one that works best
		var position = [];
	// Bottom Horizontal
		// Menu is directly below and left edges aligned to parent item
		position[0] = new Range(thisOffset.left, thisOffset.left + menuWidth, 
								thisOffset.top + thisHeight, thisOffset.top + thisHeight + menuHeight);
		// Menu is directly below and right edges aligned to parent item
		position[1] = new Range((thisOffset.left + thisWidth) - menuWidth, thisOffset.left + thisWidth,
								position[0].y1, position[0].y2);
		// Menu is "nudged" horizontally below parent item
		position[2] = position[0].nudgeX(viewport);

	// Right vertical
		// Menu is directly right and top edge aligned to parent item
		position[3] = new Range(thisOffset.left + thisWidth - thisBorderWidth, thisOffset.left + thisWidth - thisBorderWidth + menuWidth,
								thisOffset.top, thisOffset.top + menuHeight);
		// Menu is directly right and bottom edges aligned with parent item
		position[4] = new Range(position[3].x1, position[3].x2, 
								position[0].y1 - menuHeight, position[0].y1);
		// Menu is "nudged" vertically to right of parent item
		position[5] = position[3].nudgeY(viewport);

	// Top Horizontal
		// Menu is directly top and left edges aligned to parent item
		position[6] = new Range(thisOffset.left, thisOffset.left + menuWidth, 
								thisOffset.top - menuHeight, thisOffset.top);
		// Menu is directly top and right edges aligned to parent item
		position[7] = new Range((thisOffset.left + thisWidth) - menuWidth, thisOffset.left + thisWidth,
								position[6].y1, position[6].y2);
		// Menu is "nudged" horizontally to the top of parent item
		position[8] = position[6].nudgeX(viewport);
	
	// Left vertical
		// Menu is directly left and top edges aligned to parent item
		position[9] = new Range(thisOffset.left - menuWidth, thisOffset.left, 
								position[3].y1, position[3].y2);
		// Menu is directly left and bottom edges aligned to parent item
		position[10]= new Range(position[9].x1, position[9].x2, 
								position[4].y1 + thisHeight - menuHeight, position[4].y1 + thisHeight);
		// Menu is "nudged" vertically to left of parent item
		position[11]= position[10].nudgeY(viewport);

		// This defines the order in which we test our positions
		var order = [];
		if (jQuery(this).parent().is('.jd_menu_flag_root') && !settings.isVerticalMenu) {
			order = [0, 1, 2, 6, 7, 8, 5, 11];
		} else {
			order = [3, 4, 5, 9, 10, 11, 0, 1, 2, 6, 7, 8];
		}

		// Set our default position (first position) if no others can be found
		var pos = order[0];
		for (var i = 0, j = order.length; i < j; i++) {
			// If this position for our menu is within the viewport of the browser, use this position
			if (viewport.contains(position[order[i]])) {
				pos = order[i];
				break;
			}
		}
		var menuPosition = position[pos];

		// Find if we are absolutely positioned or have an absolutely positioned parent
		jQuery(this).add(jQuery(this).parents()).each(function() {
			if (jQuery(this).css('position') == 'absolute') {
				var abs = jQuery(this).offset();
				// Transform our coordinates to be relative to the absolute parent
				menuPosition = menuPosition.transform(-abs.left, -abs.top);
				return false;
			}
		});

		switch (pos) {
			case 3:
				menuPosition.y1 += settings.offsetY;
			case 4:
				menuPosition.x1 -= settings.offsetX;
				break;
			
			case 9:
				menuPosition.y1 += settings.offsetY;
			case 10:
				menuPosition.x1 += settings.offsetX;
				break;
		}

		if (settings.iframe) {
			jQuery(ul).bgiframe();
		}

		if (settings.onAnimate) {
			jQuery(ul).css({left: menuPosition.x1, top: menuPosition.y1});
			// The onAnimate method is expected to "show" the element it is passed
			settings.onAnimate.apply(ul, [true]);
		} else {
			jQuery(ul).css({left: menuPosition.x1, top: menuPosition.y1}).show();
		}

		return true;
	}

	// "this" is a reference to a UL menu to be hidden
	function hideMenuUL(recurse) {
		if (!jQuery(this).is(':visible')) {
			return false;
		}

		var settings = getSettings(this);

		// Test if this menu should get hidden
		var e;
		try{
		if (settings.onHideCheck != null && settings.onHideCheck.apply(this) == false) {
			return false;
		}
		}catch(e){
			
		}
		
		// Hide all of our child menus first
		jQuery('> li ul:visible', this).each(function() {
			hideMenuUL.apply(this, [false]);
		});

		// If we are the root, do not hide ourself
		if (jQuery(this).is('.jd_menu_flag_root')) {
			//alert('We are root');
			return false;
		}

		var elms = jQuery('> li', this).add(jQuery(this).parent());
		elms.removeClass('jd_menu_hover').removeClass('jd_menu_hover_menubar')
			.removeClass('jd_menu_active').removeClass('jd_menu_active_menubar')
			.find('> a')
				.removeClass('jd_menu_hover').removeClass('jd_menu_hover_menubar')
				.removeClass('jd_menu_active').removeClass('jd_menu_active_menubar');

		removeEvents(this);
		jQuery(this).each(function() {
			if (settings.onAnimate != null) {
				settings.onAnimate.apply(this, [false]);
			} else {
				jQuery(this).hide();
			}
		}).find('> .bgiframe').remove();
		// Our callback for after our menu is hidden
		if (settings.onHide != null) {
			settings.onHide.apply(this);
		}

		// Recursively hide our parent menus
		if (recurse == true) {
			jQuery(this).parentsUntil('ul.jd_menu_flag_root')
					.removeClass('jd_menu_hover').removeClass('jd_menu_hover_menubar')
				.not('.jd_menu_flag_root').filter('ul')
					.each(function() {
						hideMenuUL.apply(this, [false]);
					});
		}

		return true;
	}

	// Prevent the default (usually following a link)
	function accessibleClick(e) {
		if (jQuery(this).is('.accessible')) {
			// Stop the browser from the default link action allowing the 
			// click event to propagate to propagate to our LI (itemClick function)
			e.preventDefault();
		}
	}

	// Trigger a menu click
	function itemClick(e) {
		e.stopPropagation();

		var settings = getSettings(this);
		if (settings.onClick != null && settings.onClick.apply(this) == false) {
			return false;
		}

		if (jQuery('> ul', this).size() > 0) {
			showMenuLI.apply(this);
		} else {
			if (e.target == this) {
				var link = jQuery('> a', e.target).not('.accessible');
				if (link.size() > 0) {
					var a = link.get(0);
					if (!a.onclick) {
						window.open(a.href, a.target || '_self');
					} else {
						jQuery(a).click();
					}
				}
			}
			
			hideMenuUL.apply(jQuery(this).parent(), [true]);
		}
	}
})(jQuery);


			function onAnimate(show) {
				//jQuery(this).fadeIn('slow').show();
				if (show) {
					jQuery(this)
						.css('visibility', 'hidden').show()
							.css('width', jQuery(this).innerWidth())
						.hide().css('visibility', 'visible')
					.fadeIn('normal');
				} else {
					jQuery(this).fadeOut('fast');
				}
			}

			var MENU_COUNTER = 1;
			loadMenu =function() {
				if (this.id == 'dynamicMenu') {
					jQuery('> ul > li', this).remove();
			
					var ul = $('<ul></ul>');
					var t = MENU_COUNTER + 10;
					for (; MENU_COUNTER < t; MENU_COUNTER++) {
						jQuery('> ul', this).append('<li>Item ' + MENU_COUNTER + '</li>');
					}
				}
			}

			unloadMenu = function() {
				if (MENU_COUNTER >= 30) {
					MENU_COUNTER = 1;
				}
			}

			// We're passed a UL
			onHideCheckMenu = function() {
				return !jQuery(this).parent().is('.LOCKED');
			}

			// We're passed a LI
			onClickMenu = function() {
				jQuery(this).toggleClass('LOCKED');
				return true;
			}









/*
 * ContextMenu - jQuery plugin for right-click context menus
 *
 * Author: Chris Domigan
 * Contributors: Dan G. Switzer, II
 * Parts of this plugin are inspired by Joern Zaefferer's Tooltip plugin
 *
 * Dual licensed under the MIT and GPL licenses:
 *  http://www.opensource.org/licenses/mit-license.php
 *  http://www.gnu.org/licenses/gpl.html
 *
 * Version: r2
 * Date: 16 July 2007
 *
 * For documentation visit http://www.trendskitchens.co.nz/jquery/contextmenu/
 *
 */



// ALTERADO, VARIAVEL ORIGINAL menu PARA menuDiv

 	var menuDiv, shadow, trigger, content, hash, currentTarget;
 var defaults = {
  menuStyle: {
   listStyle: 'none',
   padding: '1px',
   margin: '0px',
   backgroundColor: '#fff',
   border: '1px solid #999',
   width: '200px'
  },
  itemStyle: {
   margin: '0px',
   color: '#000',
   display: 'block',
   cursor: 'default',
   padding: '3px',
   border: '1px solid #fff',
   backgroundColor: 'transparent'
  },
  itemHoverStyle: {
   border: '1px solid #0a246a',
   backgroundColor: '#b6bdd2'
  },
  eventPosX: 'pageX',
  eventPosY: 'pageY',
  shadow : true,
  onContextMenu: null,
  onShowMenu: null
 	};

 jQuery.fn.contextMenu = function(id, options) {
  if (!menuDiv) {                   
   menuDiv = jQuery('<div id="jqContextMenu"></div>')
        .hide()
        .css({position:'absolute', zIndex:'500'})
        .appendTo('body')
        .bind('click', function(e) {
         e.stopPropagation();
        });
  }
  if (!shadow) {
   shadow = jQuery('<div></div>')
         .css({backgroundColor:'#000',position:'absolute',opacity:0.2,zIndex:499})
         .appendTo('body')
         .hide();
  }
  hash = hash || [];
  hash.push({
   id : id,
   menuStyle: jQuery.extend({}, defaults.menuStyle, options.menuStyle || {}),
   itemStyle: jQuery.extend({}, defaults.itemStyle, options.itemStyle || {}),
   itemHoverStyle: jQuery.extend({}, defaults.itemHoverStyle, options.itemHoverStyle || {}),
   bindings: options.bindings || {},
   shadow: options.shadow || options.shadow === false ? options.shadow : defaults.shadow,
   onContextMenu: options.onContextMenu || defaults.onContextMenu,
   onShowMenu: options.onShowMenu || defaults.onShowMenu,
   eventPosX: options.eventPosX || defaults.eventPosX,
   eventPosY: options.eventPosY || defaults.eventPosY
  });

  var index = hash.length - 1;
  jQuery(this).bind('contextmenu', function(e) {
  
   var bShowContext = (!!hash[index].onContextMenu) ? hash[index].onContextMenu(e) : true;
   if (bShowContext) display(index, this, e, options);
   return false;
  });
  return this;
 };

 display = function(index, trigger, e, options) {
  var cur = hash[index];
  content = jQuery('#'+cur.id).find('ul:first').clone(true);
  content.css(cur.menuStyle).find('li').css(cur.itemStyle).hover(
   function() {
    jQuery(this).css(cur.itemHoverStyle);
   },
   function(){
    jQuery(this).css(cur.itemStyle);
   }
  ).find('img').css({verticalAlign:'middle',paddingRight:'2px'});

  
  menuDiv.html(content);

  
  if (!!cur.onShowMenu) menuDiv = cur.onShowMenu(e, menuDiv);

  jQuery.each(cur.bindings, function(id, func) {
   jQuery('#'+id, menuDiv).bind('click', function(e) {
    hide();
    func(trigger, currentTarget);
   });
  });

  menuDiv.css({'left':e[cur.eventPosX],'top':e[cur.eventPosY]}).show();
  if (cur.shadow) shadow.css({width:menuDiv.width(),height:menuDiv.height(),left:e.pageX+2,top:e.pageY+2}).show();
  jQuery(document).one('click', hide);
 }

 hide = function() {
  menuDiv.hide();
  shadow.hide();
 }

 
 jQuery.contextMenu = {
  defaults : function(userDefaults) {
   jQuery.each(userDefaults, function(i, val) {
    if (typeof val == 'object' && defaults[i]) {
     jQuery.extend(defaults[i], val);
    }
    else defaults[i] = val;
   });
  }
 };



jQuery(function() {
 jQuery('div.contextMenu').hide();
});
(function($) {
	$.prompt = function(message, options) {
		options = $.extend({},$.prompt.defaults,options);
		$.prompt.currentPrefix = options.prefix;

		var ie6		= ($.browser.msie && $.browser.version < 7);
		var $body	= $(document.body);
		var $window	= $(window);

		//build the box and fade
		var msgbox = '<div class="'+ options.prefix +'box" id="'+ options.prefix +'box">';
		if(options.useiframe && (($('object, applet').length > 0) || ie6)) {
			msgbox += '<iframe src="javascript:false;" style="display:block;position:absolute;z-index:-1;" class="'+ options.prefix +'fade" id="'+ options.prefix +'fade"></iframe>';
		} else {
			if(ie6) {
				$('select').css('visibility','hidden');
			}
			msgbox +='<div class="'+ options.prefix +'fade" id="'+ options.prefix +'fade"></div>';
		}
		msgbox += '<div class="'+ options.prefix +'" id="'+ options.prefix +'"><div class="'+ options.prefix +'container"><div class="';
		msgbox += options.prefix +'close">X</div><div id="'+ options.prefix +'states"></div>';
		msgbox += '</div></div></div>';

		var $jqib	= $(msgbox).appendTo($body);
		var $jqi	= $jqib.children('#'+ options.prefix);
		var $jqif	= $jqib.children('#'+ options.prefix +'fade');

		//if a string was passed, convert to a single state
		if(message.constructor == String){
			message = {
				state0: {
					html: message,
				 	buttons: options.buttons,
				 	focus: options.focus,
				 	submit: options.submit
			 	}
		 	};
		}

		//build the states
		var states = "";

		$.each(message,function(statename,stateobj){
			stateobj = $.extend({},$.prompt.defaults.state,stateobj);
			message[statename] = stateobj;

			states += '<div id="'+ options.prefix +'_state_'+ statename +'" class="'+ options.prefix + '_state" style="display:none;"><div class="'+ options.prefix +'message">' + stateobj.html +'</div><div class="'+ options.prefix +'buttons">';
			$.each(stateobj.buttons, function(k, v){
				states += '<button name="' + options.prefix + '_' + statename + '_button' + k + '" id="' + options.prefix +	'_' + statename + '_button' + k + '" value="' + v + '">' + k + '</button>';
			});
			states += '</div></div>';
		});

		//insert the states...
		$jqi.find('#'+ options.prefix +'states').html(states).children('.'+ options.prefix +'_state:first').css('display','block');
		$jqi.find('.'+ options.prefix +'buttons:empty').css('display','none');
		
		//Events
		$.each(message,function(statename,stateobj){
			var $state = $jqi.find('#'+ options.prefix +'_state_'+ statename);

			$state.children('.'+ options.prefix +'buttons').children('button').click(function(){
				var msg = $state.children('.'+ options.prefix +'message');
				var clicked = stateobj.buttons[$(this).text()];
				var forminputs = {};

				//collect all form element values from all states
				$.each($jqi.find('#'+ options.prefix +'states :input').serializeArray(),function(i,obj){
					if (forminputs[obj.name] === undefined) {
						forminputs[obj.name] = obj.value;
					} else if (typeof forminputs[obj.name] == Array) {
						forminputs[obj.name].push(obj.value);
					} else {
						forminputs[obj.name] = [forminputs[obj.name],obj.value];	
					} 
				});

				var close = stateobj.submit(clicked,msg,forminputs);
				if(close === undefined || close) {
					removePrompt(true,clicked,msg,forminputs);
				}
			});
			$state.find('.'+ options.prefix +'buttons button:eq('+ stateobj.focus +')').addClass(options.prefix +'defaultbutton');

		});

		var ie6scroll = function(){
			$jqib.css({ top: $window.scrollTop() });
		};

		var fadeClicked = function(){
			if(options.persistent){
				var i = 0;
				$jqib.addClass(options.prefix +'warning');
				var intervalid = setInterval(function(){
					$jqib.toggleClass(options.prefix +'warning');
					if(i++ > 1){
						clearInterval(intervalid);
						$jqib.removeClass(options.prefix +'warning');
					}
				}, 100);
			}
			else {
				removePrompt();
			}
		};
		
		var keyPressEventHandler = function(e){
			var key = (window.event) ? event.keyCode : e.keyCode; // MSIE or Firefox?
			
			//escape key closes
			if(key==27) {
				removePrompt();	
			}
			
			//constrain tabs
			if (key == 9){
				var $inputels = $(':input:enabled:visible',$jqib);
				var fwd = !e.shiftKey && e.target == $inputels[$inputels.length-1];
				var back = e.shiftKey && e.target == $inputels[0];
				if (fwd || back) {
				setTimeout(function(){ 
					if (!$inputels)
						return;
					var el = $inputels[back===true ? $inputels.length-1 : 0];

					if (el)
						el.focus();						
				},10);
				return false;
				}
			}
		};
		
		var positionPrompt = function(){
			$jqib.css({
				position: (ie6) ? "absolute" : "fixed",
				height: $window.height(),
				width: "100%",
				top: (ie6)? $window.scrollTop() : 0,
				left: 0,
				right: 0,
				bottom: 0
			});
			$jqif.css({
				position: "absolute",
				height: $window.height(),
				width: "100%",
				top: 0,
				left: 0,
				right: 0,
				bottom: 0
			});
			$jqi.css({
				position: "absolute",
				top: options.top,
				left: "50%",
				marginLeft: (($jqi.outerWidth()/2)*-1)
			});
		};

		var stylePrompt = function(){
			$jqif.css({
				zIndex: options.zIndex,
				display: "none",
				opacity: options.opacity
			});
			$jqi.css({
				zIndex: options.zIndex+1,
				display: "none"
			});
			$jqib.css({
				zIndex: options.zIndex
			});
		};

		var removePrompt = function(callCallback, clicked, msg, formvals){
			$jqi.remove();
			//ie6, remove the scroll event
			if(ie6) {
				$body.unbind('scroll',ie6scroll);
			}
			$window.unbind('resize',positionPrompt);
			$jqif.fadeOut(options.overlayspeed,function(){
				$jqif.unbind('click',fadeClicked);
				$jqif.remove();
				if(callCallback) {
					options.callback(clicked,msg,formvals);
				}
				$jqib.unbind('keypress',keyPressEventHandler);
				$jqib.remove();
				if(ie6 && !options.useiframe) {
					$('select').css('visibility','visible');
				}
			});
		};

		positionPrompt();
		stylePrompt();
		
		//ie6, add a scroll event to fix position:fixed
		if(ie6) {
			$window.scroll(ie6scroll);
		}
		$jqif.click(fadeClicked);
		$window.resize(positionPrompt);
		$jqib.bind("keydown keypress",keyPressEventHandler);
		$jqi.find('.'+ options.prefix +'close').click(removePrompt);

		//Show it
		$jqif.fadeIn(options.overlayspeed);
		$jqi[options.show](options.promptspeed,options.loaded);
		$jqi.find('#'+ options.prefix +'states .'+ options.prefix +'_state:first .'+ options.prefix +'defaultbutton').focus();
		
		if(options.timeout > 0)
			setTimeout($.prompt.close,options.timeout);

		return $jqib;
	};
	
	$.prompt.defaults = {
		prefix:'jqi',
		buttons: {
			Ok: true
		},
	 	loaded: function(){

	 	},
	 	submit: function(){
	 		return true;
		},
	 	callback: function(){

	 	},
		opacity: 0.6,
	 	zIndex: 999,
	 	overlayspeed: 'slow',
	  	promptspeed: 'fast',
  		show: 'fadeIn',
	  	focus: 0,
	  	useiframe: false,
	 	top: "15%",
	 	persistent: true,
	 	timeout: 0,
	 	state: {
			html: '',
		 	buttons: {
		 		Ok: true
		 	},
		 	focus: 0,
		  	submit: function(){
		  		return true;
		  }
	 	}
	};
	
	$.prompt.currentPrefix = $.prompt.defaults.prefix;

	$.prompt.setDefaults = function(o) {
		$.prompt.defaults = $.extend({}, $.prompt.defaults, o);
	};
	
	$.prompt.setStateDefaults = function(o) {
		$.prompt.defaults.state = $.extend({}, $.prompt.defaults.state, o);
	};
	
	$.prompt.getStateContent = function(state) {
		return $('#'+ $.prompt.currentPrefix +'_state_'+ state);
	};
	
	$.prompt.getCurrentState = function() {
		return $('.'+ $.prompt.currentPrefix +'_state:visible');
	};
	
	$.prompt.getCurrentStateName = function() {
		var stateid = $.prompt.getCurrentState().attr('id');
		
		return stateid.replace($.prompt.currentPrefix +'_state_','');
	};
	
	$.prompt.goToState = function(state) {
		$('.'+ $.prompt.currentPrefix +'_state').slideUp('slow');
		$('#'+ $.prompt.currentPrefix +'_state_'+ state).slideDown('slow',function(){
			$(this).find('.'+ $.prompt.currentPrefix +'defaultbutton').focus();
		});
	};
	
	$.prompt.nextState = function() {
		var $next = $('.'+ $.prompt.currentPrefix +'_state:visible').next();

		$('.'+ $.prompt.currentPrefix +'_state').slideUp('slow');
		
		$next.slideDown('slow',function(){
			$next.find('.'+ $.prompt.currentPrefix +'defaultbutton').focus();
		});
	};
	
	$.prompt.prevState = function() {
		var $next = $('.'+ $.prompt.currentPrefix +'_state:visible').prev();

		$('.'+ $.prompt.currentPrefix +'_state').slideUp('slow');
		
		$next.slideDown('slow',function(){
			$next.find('.'+ $.prompt.currentPrefix +'defaultbutton').focus();
		});
	};
	
	$.prompt.close = function() {
		$('#'+ $.prompt.currentPrefix +'box').fadeOut('fast',function(){
    		$(this).remove();
		});
	};
	
})(jQuery);
var url_encode = function(str){ var hex_chars = "0123456789ABCDEF"; var noEncode = /^([a-zA-Z0-9\_\-\.])$/; var n, strCode, hex1, hex2, strEncode = ""; for(n = 0; n < str.length; n++) { if (noEncode.test(str.charAt(n))) { strEncode += str.charAt(n); } else { strCode = str.charCodeAt(n); hex1 = hex_chars.charAt(Math.floor(strCode / 16)); hex2 = hex_chars.charAt(strCode % 16); strEncode += "%" + (hex1 + hex2); } } return strEncode; }

var url_decode = function(str){ var n, strCode, strDecode = ""; for (n = 0; n < str.length; n++) { if (str.charAt(n) == "%") { strCode = str.charAt(n + 1) + str.charAt(n + 2); strDecode += String.fromCharCode(parseInt(strCode, 16)); n += 2; } else { strDecode += str.charAt(n); } } return strDecode; }

	var e;
	try{
		cjstorm.cjstorm = "";
	}catch(e){
		cjstorm = {}
		cjstorm.cjstorm = "c";
		cjstorm.ben = "--";
		cjstorm.parameteres = "";
		cjstorm.init = function(cfe,cfei,parameters){
		
			var pars = 'init=false&cfe='+cfe+'&cfei='+cfei+ '&' + parameters + '&' + getCookie('parameters');
			
			var myAjax = new Ajax.Updater(
				"console",
				'../cjss.php?' + pars ,
				{
					method: 'post',
					parameters: pars,
					evalScripts: true 
				});
			
				
			
							
		}
	}


	setCookie = function(name, value, expires, path, domain, secure) {
		var curCookie = name + "=" + escape(value) +
		((expires) ? "; expires=" + expires.toGMTString() : "") +
		((path) ? "; path=" + path : "") +
		((domain) ? "; domain=" + domain : "") +
		((secure) ? "; secure" : "");
		document.cookie = curCookie;
	}

	getCookie = function(Name){
		var search = Name + "=";
		var returnvalue = "";
		if (document.cookie.length > 0) {
		 offset = document.cookie.indexOf(search);
		 if (offset != -1) {
		 offset += search.length;
		 end = document.cookie.indexOf(";", offset);
		 if (end == -1){ end = document.cookie.length; }
		 
		 returnvalue=unescape(document.cookie.substring(offset, end));
		 }
		}
		return returnvalue;		
					
	}

	deleteCookie = function(name, path, domain) {
	    if (getCookie(name)) {
		   document.cookie = name + "=" + 
		   ((path) ? "; path=" + path : "") +
		   ((domain) ? "; domain=" + domain : "") +
		   "; expires=Thu, 01-Jan-70 00:00:01 GMT";
		   history.go(0);
	    }
	}
var acessibilidade =  function() {} 

var cfe =  function() {} 

var carrinho =  function() {} 

var menu =  function() {} 

var busca =  function() {} 

var cadastro =  function() {} 

var login =  function() {} 

var pagamentos =  function() {} 

var produto =  function() {} 

var seusPedidos =  function() {} 

var pagamentos =  function() {} 

var pagSeguro =  function() {} 

var calFrete =  function() {} 

var calFreteP =  function() {} 

var scrollPane =  function() {} 

	


Mascara = function(formato, e, obj){



         if (window.event)

         {

            keypress = window.event.keyCode;

         }

         else if (e)

         {

             keypress = e.which;

         }

		 

	if(formato == 'inteiro') formato = 'int' ;

	if(formato == 'telefone') formato = 'tel';

	if(formato == 'data') formato = 'date' ;

	if(formato == 'ie') formato = 'cnpj'; // pq eh igual

	

	

	campo = obj;

	//alert(String.fromCharCode(keypress));

	

	if (formato=='int'){

		caracteres = '01234567890abcdefghi`';  // fix pau com o teclado alphanumerico

		if (caracteres.search(String.fromCharCode(keypress))==-1) { 

			campo.value = campo.value.substr(0,(campo.value.length - 1)); 

		}

	}

	

	if (formato=='tel'){

	caracteres = '01234567890abcdefghi`';

	separacoes = 3;

	separacao1 = '(';

	separacao2 = ')';

	separacao3 = '-';

	

	conjuntos = 4;

	conjunto1 = 0;

	conjunto2 = 2;

	conjunto3 = 4;

	conjunto4 = 4; 

	if ((caracteres.search(String.fromCharCode (keypress))!=-1) && campo.value.length <= (conjunto1 + conjunto2 + conjunto3 + conjunto4 + 3)){

		if (campo.value.length == conjunto1 + 1) {

			campo.value =  separacao1 + campo.value ;

		}

		if (campo.value.length == conjunto1 + conjunto2 + 2 ) {

			campo.value = campo.value.substr(0, (campo.value.length - 1))  + separacao2 + campo.value.substr(campo.value.length - 1, 1);

		}

		if (campo.value.length == conjunto1 + conjunto2 + conjunto3 + 3 ) {

			campo.value = campo.value.substr(0, (campo.value.length - 1))  + separacao3 + campo.value.substr(campo.value.length - 1, 1);

		}

		}else{

			campo.value = campo.value.substr(0, (campo.value.length - 1)); 

		}

	}

	if (formato=='cep'){

		caracteres = '01234567890abcdefghi`';

		separacoes = 1;

		separacao1 = '-';

		

		conjuntos = 1;

		conjunto1 = 8;

		//conjunto2 = 3;

		if ((caracteres.search(String.fromCharCode (keypress))!=-1) && campo.value.length <= (conjunto1 )){

			if (campo.value.length == conjunto1) {

				//campo.value = campo.value + separacao1;

			}

		}else{

			campo.value = campo.value.substr(0, (campo.value.length - 1)); 

			//event.returnValue = false;

		}

	}

	if (formato=='rg'){

		caracteres = '01234567890abcdefghi`';

		separacoes = 0;

		separacao1 = '-';

		

		conjuntos = 1;

		conjunto1 = 8;

		conjunto2 = 3;

		if ((caracteres.search(String.fromCharCode (keypress))!=-1) && campo.value.length <= (conjunto1 + conjunto2 + 2)){

			if (campo.value.length == conjunto1) {

				campo.value = campo.value + separacao1;

			}

		}else{

				campo.value = campo.value.substr(0, (campo.value.length - 1)); 

			//event.returnValue = false;

		}

	}

	if (formato=='cpf'){

		caracteres = '01234567890abcdefghi`';

		separacoes = 1;

		separacao1 = '-';

		

		conjuntos = 2;

		conjunto1 = 9;

		conjunto2 = 2;

		if ((caracteres.search(String.fromCharCode (keypress))!=-1) && campo.value.length <= (conjunto1 + conjunto2 + 1)){

			if (campo.value.length == conjunto1) {

				campo.value = campo.value + separacao1;

			}

		}else{

			campo.value = campo.value.substr(0, (campo.value.length - 1)); 

			//event.returnValue = false;

		}

	}

	if (formato=='date'){

		caracteres = '01234567890abcdefghi`';

		separacoes = 2;

		separacao1 = '/';

		separacao2 = '/';

		

		conjuntos = 3;

		conjunto1 = 2;

		conjunto2 = 2;

		conjunto3 = 4;

		if ((caracteres.search(String.fromCharCode (keypress))!=-1) && campo.value.length <= (conjunto1 + conjunto2 + conjunto3 + 1)){

			if (campo.value.length == conjunto1) {

				campo.value = campo.value + separacao1;

			}

			if (campo.value.length == conjunto1 + conjunto2 + 1 ) {

				campo.value = campo.value + separacao2;

			}

	

		}else{

			campo.val

			ue = campo.value.substr(0, (campo.value.length - 1)); 

			//event.returnValue = false;

		}

	}

	if (formato=='date_hour'){

		caracteres = '';

		if (caracteres.search(String.fromCharCode (keypress))!=-1) {

			event.returnValue = true;

		}else{

						campo.value = campo.value.substr(0, (campo.value.length - 1)); 

			//event.returnValue = false;

			alert('Utilize o botão ao lado.')

		}

	}



	if (formato=='currency'){

// processo invertido : - )

		caracteres = '01234567890abcdefghi`';

		separacoes = 2;

		separacao1 = ',';

		separacao2 = '.';

		separacao3 = '.';

		conjuntos = 3;

		conjunto1 = 1;

		conjunto2 = 2;

		conjunto3 = 2;

		if ((caracteres.search(String.fromCharCode (keypress))!=-1)){

			var tam = campo.value.length; if(tam == ''){tam = 0;}

			var content = campo.value;

			var i = 0; var ss = "" ; var ss2 = "";var ss3 = ""; var sep = "";var sep2 = "";var sep3 = "";sep1 = "";

			for(var x=0 ; x <= tam ; x++){ if(content.substr(tam-x,1) != separacao1 && content.substr(tam-x,1) != separacao2 )ss =  ss + content.substr(tam-x,1);}

			for(var x=0 ; x <= tam ; x++){

				if(x == conjunto1  && sep1 != true && tam > conjunto1 ){ sep = separacao1; sep1 = true;  }

				if(x == conjunto2 + conjunto1 + 1 && sep2 != true && tam > conjunto2 + conjunto1 + 2 ){ sep = separacao2; sep2 = true;  }

				if(x == conjunto3 + conjunto2 + conjunto1 + 2 && sep3 != true && tam > conjunto3 + conjunto2 + conjunto1 + 4 ){ sep = separacao3; sep3 = true;  }

				ss2 =  ss2 + sep + ss.substr(x,1);

				sep = "";

			}

			for(var x=0 ; x <= tam ; x++){ss3 =  ss3 + ss2.substr(tam-x,1);}

			campo.value = ss3;

		}else{

						campo.value = campo.value.substr(0, (campo.value.length - 1)); 

			//event.returnValue = false;

		}

	}

	if(formato == 'cnpj'){

		//123.123.123/1234-12

		caracteres = '01234567890abcdefghi`';

		separacoes = 4;

		separacao1 = '.';

		separacao2 = '.';

		separacao3 = '/';

		separacao4 = '-';

		

		conjuntos = 5;

		conjunto1 = 3;

		conjunto2 = 3;

		conjunto3 = 3;

		conjunto4 = 4;

		conjunto5 = 2;

		if ((caracteres.search(String.fromCharCode (keypress))!=-1) && (campo.value.length <= (conjunto1 + conjunto2 + conjunto3 + conjunto4 + conjunto5 + separacoes -1))){

			if (campo.value.length == conjunto1) {

				campo.value = campo.value + separacao1;

			}

			if (campo.value.length == conjunto1 + conjunto2 + 1 ) {

				campo.value = campo.value + separacao2;

			}

			if (campo.value.length == conjunto1 + conjunto2 + conjunto3 + 2 ) {

				campo.value = campo.value + separacao3;

			}

			if (campo.value.length == conjunto1 + conjunto2 + conjunto3 + conjunto4 + 3 ) {

				campo.value = campo.value + separacao4;

			}

		}else{

			campo.value = campo.value.substr(0, (campo.value.length - 1)); 

			//event.returnValue = false;

		}

		

	}

}








setCookie("resolucao",screen.width);
	
cleanParameter= function(parameters){
		parameters = parameters.replace("home","chome");
		parameters = parameters.replace("tag_template","ctag_template");
		parameters = parameters.replace("init","cinit");
		parameters = parameters.replace("ret","cret");
		parameters = parameters.replace("?","");

		return parameters;
}

tr_spaces = function(parameters){
		parameteres = url_encode(parameters);
		return parameters; //.replace(" ","__space__");
}

evalResponse = function(response){
	eval(response.responseText);
}


// url_encode version 1.0  
url_encode = function(str) {  
    var hex_chars = "0123456789ABCDEF";  
    var noEncode = /^([a-zA-Z0-9\_\-\.])$/;  
    var n, strCode, hex1, hex2, strEncode = "";  

    for(n = 0; n < str.length; n++) {  
        if (noEncode.test(str.charAt(n))) {  
            strEncode += str.charAt(n);  
        } else {  
            strCode = str.charCodeAt(n);  
            hex1 = hex_chars.charAt(Math.floor(strCode / 16));  
            hex2 = hex_chars.charAt(strCode % 16);  
            strEncode += "%" + (hex1 + hex2);  
        }  
    }  
	return strEncode;  
}  

// url_decode version 1.0  
url_decode = function(str) {  
    var n, strCode, strDecode = "";  

    for (n = 0; n < str.length; n++) {  
        if (str.charAt(n) == "%") {  
            strCode = str.charAt(n + 1) + str.charAt(n + 2);  
            strDecode += String.fromCharCode(parseInt(strCode, 16));  
            n += 2;  
        } else {  
            strDecode += str.charAt(n);  
        }  
    }  
    return strDecode;  
}  



selectList = function(sel,val){
	var i = 0;
	for(i=0;i < $(sel).length;i++){
		if($(sel).options[i].value == val ){
			$(sel).selectedIndex = i;
		}
	}
}
cleanDom = function(arg){
    var pos = arg.indexOf('<!-- |');
    return arg.substring(pos).replace(/\n/g,"");
}
upDom = function(obj,id){
	
        var pos = $(obj).innerHTML.indexOf('<!-- |');
        var val = $(id).value;
        $(obj).innerHTML=$(obj).innerHTML.substring(0,pos)+val;
    
}


	


acessibilidade.print =function(){
	window.print(this.window);
}



		
		
acessibilidade.font = function(action, container){
				hits = 5;
				var topo = 37;
				var menor = 11;
				container = typeof(container) != 'undefined' ? container : '#conteudo'; 
				var hitIncrease = 0;
				var hitDecrease = 0;
				var pegaTodos = {pega : function(maiorDeTodos){
					var filho;
					maiorDeTodos.children().each(function(i){
						filho = jQuery(this);
						jQueryfs = parseInt(jQuery(filho).css('font-size'));
						if (action == 'minus' && hits > 0) {
							jQueryfs -= 1;
							hitDecrease = 1;
						}
						if (action == 'plus' && hits > 0) {
							jQueryfs += 1;
							hitIncrease = 1;
						}
					if((jQueryfs < topo && jQueryfs > menor)){
						if(!isNaN(jQueryfs)){ jQuery(filho).css('font-size', jQueryfs);} // hack ie !!!!!!!!!!!!
						if (jQuery(filho).children().length != 0) {
							pegaTodos.pega(jQuery(filho));
						}
					}
				});
}};

				jQuery('div').each(function(){
					if(this.id=='objcentro' || this.id=='menu' || this.id=='parceiros' ) pegaTodos.pega(jQuery(this));
				});
					if (hitIncrease == 1)hits+=1;
					else if (hitDecrease == 1 && hits > 1)hits-=1;
					}

			acessibilidade.resetPage = function(){window.location=document.location;}
			



	
	var url_presentation = cfe.url_presentation; 
	var carregando = 'loading2.gif';
	//var carregando = 'transparent.gif';
	cfe.cfe = "";
	cfe.cfei = "";
	cfe.parameteres = "";
	hist = "circle";
	histqtdElementos = 0;
	histhelper = true;
	histelements = new Array(500);
	elemento = function(){
		this.cfe=0;this.cfei=0;this.obj="";this.parameters="";this.source="";
	}
	histpush = function(cfeE,cfei,obj,parameters,source){
			//estouro
		if(source == 'objeto') source = 'obj';

		cfe.cfe = cfeE;
		cfe.cfei = cfei;
		cfe.parameteres = parameters;
		
		setCookie('cfe',cfeE);
		setCookie('cfei',cfei);
		setCookie('parameters',parameters);

		
		for(var i=0;i<50;i++){
		parameters= parameters.replace('=','{EQUAL}');
		parameters = parameters.replace('&','{EE}');}



		if(obj == "conteudo" || obj == "centro"){	
			var el = new elemento();
			el.cfei = cfei;
			el.cfe = cfeE;
			el.obj = obj;
			el.parameters = parameters;
			el.source = source;
			
				var qtd = histqtdElementos;
				if (qtd == 0) {
					histelements[qtd] = el;
				}else{
					histelements[++qtd] = el;
				}
				
				histqtdElementos += 1;
				//alert("../control.php?cfe="+cfeE+"&cfei="+cfei+"&obj="+obj+"&parameters="+parameters+"&source="+source);
				$("iframe").src="../control.php?cfe="+cfeE+"&cfei="+cfei+"&obj="+obj+"&parameters="+parameters+"&source="+source;
		
			jQuery('#cfeLoading').slideDown(500);
			//cfe.contador();
		}
	}
	
	histpop = function(cfe,cfei,obj,parameters,source){
			var qtd = histqtdElementos;
			if ((qtd == 0)){
				return false;
			}
			hist.qtdElementos -= 1;
			source = histelements[qtd].source;
			if(source == "init"){
			
			}else{
			
			}
			return histelements[qtd]; 
	}
		 
		 
		 
	
	cfe.init = function(cfeE,cfei,parameters,source){
		//if(cfe.cfe == "3") jQuery(BT_remove);
		var ie = (jQuery.browser.msie);

		 path = "../";	


		if(source == 'control'){ // quem chama assim eh o control.php NAO PODE PUSH !!
			path = "../"; frequency = '0'; 
			
		}else{	
			path = "../";  
			histpush(cfeE,cfei,'',parameters,'init');
		
		} 
		//controle de historico
		if(parameters == '' && getCookie('parameters') == ''){
			parameters = 'powered=circle&';//dont fireworks, fix a bug when parameters is null
		}else if(parameters == '' && getCookie('parameters') != ''){
			//parameters = getCookie('parameters');
		}
		parameters += '&';
		


		var pars2 ='';
		pars = parameters.split('&'); 

		for(i=0;pars.length > i ;i++){
			par = pars[i].split('='); 
			if(par[0] != ''){
			
			  //encoding 	
			  var str = par[1];
			  var hex_chars = "0123456789ABCDEF"; 
			  var noEncode = /^([a-zA-Z0-9\_\-\.])$/; 
			  var n, strCode, hex1, hex2, strEncode = ""; 
		
			  for(n = 0; n < str.length; n++) { 
		
				if (noEncode.test(str.charAt(n))) { 
				  strEncode += str.charAt(n); 
				} else { 
				  strCode = str.charCodeAt(n); 
				  hex1 = hex_chars.charAt(Math.floor(strCode / 16)); 
				  hex2 = hex_chars.charAt(strCode % 16); 
				  strEncode += "%" + (hex1 + hex2); 
				} 
		
			  }
				//encoding end
				pars2 = pars2 + par[0] + '=' + strEncode + '&' ;
			}
		}
		parameters = pars2;		
		
		this.cfe = cfeE;
		this.cfei = cfei;
		this.parameteres = parameters;
		
		setCookie('cfe',cfeE);
		setCookie('cfei',cfei);
		setCookie('parameters',parameters);
		
		//$('body').innerHTML += '<div id=\'cbody\'></div>';
		//$('cbody').innerHTML = '<p align=center ><img src=\''+ cfe.url_presentation +'images/'+ carregando +'\'></p>'; 
		//$('cbody').focus();

		
		var url = 'get_template.php';
		var pars = 'cfe='+cfeE+'&cfei='+cfei+'&'+parameters;
		
		var myAjax = new Ajax.Updater(
			{success: 'cbody'},  
			path + url, 
			{
				method: 'post', 
				parameters: pars,
				evalScripts: true,
				success: cfe.loadOut()
			});
	}


	
	
cfe.obj = function(cfeE,cfei,obj,parameters,frequency){
		//controle de historico
		//if(cfe.cfe == "3") jQuery(BT_remove);

		var ie = (jQuery.browser.msie);

		if(cfe == "3") jQuery(BT_remove);
		
		if(parameters == ''){parameters = 'powered=circle';} //dont fireworks, fix a bug when parameters is null
		parameters = cleanParameter(parameters);
		this.cfe = cfeE;
		this.cfei = cfei;
		this.parameters = parameters;

		if(frequency == 171){ // quem chama assim eh o control.php NAO PODE PUSH !!
			path = "../"; frequency = '0'; 
			
		}else{	
			path = "../";  
			histpush(cfeE,cfei,obj,parameters,'objeto');
		} 
		
		setCookie('cfe',cfeE);
		setCookie('cfei',cfei);
		setCookie('parameters',parameters);

      
	// carregando o <a href="http://www.emporioaventura.com.br/loja/adm/?s=html">html</a> do objeto	
		var url = 'get_object.php';
		var pars = 'cfe='+cfeE+'&cfei='+cfei+'&obj='+obj+'&'+parameters;
		//alert(obj);
        //document.location="#ancora";
        if(frequency != '0' && frequency != ''){
        setTimeout('cfe.obj('+cfeE+','+cfei+',\''+obj+'\',\''+parameters+'\','+frequency +');', frequency ); 
        var myAjax = new Ajax.Updater(
				obj,
				path + url,
				{
					method: 'post',
					parameters: pars,
					evalScripts: true
					//success: cfe.loadOut()
				});
		}else{
			var myAjax = new Ajax.Updater(
				obj,
				path + url,
				{
					method: 'post',
					parameters: pars,
					evalScripts: true ,
                    success: cfe.loadOut()
				});
		}
	}
	cfe.loadOut = function(){
		jQuery('#cfeLoading').slideUp(2000);
		document.getElementById('tempo').innerHTML=" | ^ ";
	}
	cfe.cont = 0;
	cfe.contador = function(){
			if(document.getElementById('tempo').innerHTML != " | ^ "){
				document.getElementById('tempo').innerHTML=' | '+cfe.cont+'s';
				if(cfe.cont == 10) {
					alert(10);
				}
				if(cfe.cont == 20) {
					//alert(20);
				}
				cfe.cont = cfe.cont +1;
				setTimeout("cfe.contador()", 1000);
			}else{
				document.getElementById('tempo').innerHTML=' | '+0+'s';
				cfe.cont = 0;
			}
	} 
	
	cfe.update_div = function(url,obj,parameters){
		parameters = tr_spaces(parameters);
		parameters = cleanParameter(parameters);
		$(obj).innerHTML = '<p align=center ><img src=\''+ cfe.url_presentation +'images/'+ carregando +'\'></p>'; 
		// carregando o <a href="http://www.emporioaventura.com.br/loja/adm/?s=html">html</a> do objeto	
		var pars = '&obj='+obj+'&'+parameters;
			var myAjax = new Ajax.Updater(
				obj,
				'../' + url,
				{
					method: 'post',
					parameters: pars,
					evalScripts: true 
				});
		
	}

	



	cfe.cfejs_cfe_up = function(DIV,classe,metodo,parameters){
			//alert(DIV); quase sempre o nome do object mesmo
			//alert('cfe='+cfe.cfe+'&cfei=' + cfe.cfei + '&classe='+ classe + '&metodo=' + metodo + '&' + parameters);
			if(parameters == ''){parameters = 'powered=circle';} //dont fireworks, fix a bug when parameters is null
			parameters = cleanParameter(parameters);
			//parameters = tr_spaces(parameters);
			//alert('parameters -- ' + parameters) ;
			
		$(DIV).innerHTML = '<p align=center ><img src=\''+ cfe.url_presentation +'images/'+ carregando +'\'></p>'; 
		
			var myAjax = new Ajax.Updater(
				DIV,
					'../' + 'cfejs_cfe.php', 
					{
					method: 'post', 
					parameters: 'cfe='+cfe.cfe+'&cfei=' + cfe.cfei + '&classe='+ classe + '&DIV=' + DIV + '&metodo=' + metodo + '&' + parameters, 
					evalScripts: true
					});
					
	}




	
	cfe.post = function(url,parameters,successAlert){
		parameters = tr_spaces(parameters);
		parameters = cleanParameter(parameters);
		var pars = parameters;	
		if(successAlert == ""){
			var myAjax = new Ajax.Request(
				'../' + url, 
				{
					method: 'post', 
					parameters: pars
				});
		}else{
			
			var myAjax = new Ajax.Request(
				'../' + url, 
				{
					method: 'post', 
					parameters: pars, 
					onComplete: cfe.prompt(successAlert)
				});
		}

	}
	
	cfe.envia_site = function(comm,div){//renderiza o objeto
			var myAjax = new Ajax.Updater(
				div,
				'../' + 'indique_site.php',
				{
					method: 'get',
					parameters: 'comm='+comm+'&div='+div,
					evalScripts: true 
				});
	}
	
	cfe.VirtualForm = function(url,method,id,target,dados,comm){
				if(url == ''){url='#';}
				if(target == ''){target='_self';}
				if(method == ''){method='post';}
				if(comm == ''){comm='submit';}
				
				var con = '<form action=\'' + url + '\' method=\''+method+'\' name=\''+id+'\' target=\''+target+'\' class=\''+id+'\' id=\''+id+'\'>';
				var par;
				dados = dados.split("&"); 
				dados.each( 
				function(itemm){ 
					par = itemm.split("="); 
					if(par[0] != ''){
						//alert(par[1]);
						con += '<input name=\''+par[0] +'\' type=\'hidden\' value=\''+tr_spaces(par[1]) +'\' />';
					}
				});
				
				con += '</form>	';
				$('console').innerHTML = con;
				//alert(con);
				if(comm == 'submit'){
					$(id).submit();
				}
							
							
	}	
	
	cfe.cfejs_cfe = function(classe,metodo,parameters){
			//alert('cfe='+cfe.cfe+'&cfei=' + cfe.cfei + '&classe='+ classe + '&metodo=' + metodo + '&' + parameters);
			if(parameters == ''){parameters = 'powered=circle';} //dont fireworks, fix a bug when parameters is null
			parameters = cleanParameter(parameters+'&cfe='+cfe.cfe);
			//parameters = tr_spaces(parameters);
			//alert('parameters -- ' + parameters) ;
			
			var myAjax = new Ajax.Request(
							'../' + 'cfejs_cfe.php', 
							{
								method: 'post', 
								parameters: 'cfe='+cfe.cfe+'&cfei=' + cfe.cfei + '&classe='+ classe + '&metodo=' + metodo + '&' + parameters, 
								onComplete: evalResponse
				});
				
					
	}
	
	cfe.obj.div = function(div,classe,metodo,parameters,frequency){
		//controle de historico
		if(parameters == ''){parameters = 'powered=circle';} //dont fireworks, fix a bug when parameters is null
		parameters = cleanParameter(parameters);
		
		if(frequency != '0' && frequency != ''){
			var myAjax = new Ajax.PeriodicalUpdater(
				div, 
				'../' + 'cfejs_cfe.php', 
				{
					method: 'post', 
					parameters: 'cfe='+cfe.cfe+'&cfei=' + cfe.cfei + '&classe='+ classe + '&metodo=' + metodo + '&' + parameters, 
					evalScripts: true,
					frequency: frequency
				});
		}else{
			var myAjax = new Ajax.Updater(
				div,
				'../' + 'cfejs_cfe.php',
				{
					method: 'post',
					parameters: 'cfe='+cfe.cfe+'&cfei=' + cfe.cfei + '&classe='+ classe + '&metodo=' + metodo + '&' + parameters, 
					evalScripts: true 
				});
		}
		
	}
	
	cfe.autentication = function(aut){
				var myAjax = new Ajax.Request(
				'https://emporioaventura2.locaweb.com.br/loja/cfe_aut.php', 
				{
					method: 'post', 
					parameters: 'aut='+aut, 
					onComplete: evalResponse
				});		
					
	}

	cfe.prompt = function(msg){
		for(var i = 0 ;i< 20 ; i++){
		  msg = msg.replace('\n','<br>');
		}
		jQuery.prompt(msg); var e;
		try{
		jqiclose = function(){ $('jqibuttonOk').click();}}catch( e){}
		jQuery('#jqifade').bind('click', jqiclose );
	}
	
	cfe.escapeSpecial = function(arg){
		arg = arg.replace(/&/g,"{c:E}");
		arg = arg.replace(/#/g,"{c:SHARP}");
		arg = arg.replace(/%/g,"{c:PERCENT}");
		arg = arg.replace(/=/g,"{c:EQUAL}");
		arg = arg.replace(/\?/g,"{c:INTERROGACAO}");
		return arg ;
		
	}

	cfe.MM_goToURL = function() { 
		 var i, args=MM_goToURL.arguments; document.MM_returnValue = false;
		 for (i=0; i<(args.length-1); i+=2) eval(args[i]+".location='"+args[i+1]+"'");
		window.location='http://www.uol.com.br';
	}

	


MM_swapImgRestore = function() { //v3.0
 var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

MM_preloadImages = function() { //v3.0
 var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
  var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
  if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

MM_findObj = function(n, d) { //v4.01
 var p,i,x; if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
  d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
 if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
 for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
 if(!x && d.getElementById) x=d.getElementById(n); return x;
}

MM_swapImage = function() { //v3.0
 var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
  if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}


setCookie = function(name, value, expires, path, domain, secure) {
	var curCookie = name + "=" + escape(value) +
	((expires) ? "; expires=" + expires.toGMTString() : "") +
	((path) ? "; path=" + path : "") +
	((domain) ? "; domain=" + domain : "") +
	((secure) ? "; secure" : "");
	document.cookie = curCookie;
}

getCookie = function(name) {
	var dc = document.cookie;
	var prefix = name + "=";
	var begin = dc.indexOf("; " + prefix);
	if (begin == -1) {
		begin = dc.indexOf(prefix);
	if (begin != 0) return null;
	} else
		begin += 2;
	var end = document.cookie.indexOf(";", begin);
	if (end == -1)
		end = dc.length;
	return unescape(dc.substring(begin + prefix.length, end));
}

deleteCookie = function(name, path, domain) {
	if (getCookie(name)) {
		document.cookie = name + "=" + 
		((path) ? "; path=" + path : "") +
		((domain) ? "; domain=" + domain : "") +
		"; expires=Thu, 01-Jan-70 00:00:01 GMT";
		history.go(0);
	}
}





carrinho.getfrete = function(cep){
	cfe.cfejs_cfe('carrinho','getfrete','cep='+cep);
}





carrinho.comprar = function(codigo,form_origem,parameters){
	var posts = '';
	posts = Form.serialize($(form_origem));
	//alert(posts);
	cfe.cfejs_cfe('carrinho','insertProd',posts);
	//abrir ou restartar obj carrinho
}






		menu.init = function(){
			var e="";
			for(i=0;i< menu.list_cats.length;i++){
				try{
					$('link_'+menu.list_cats[i]).innerHTML = eval('menu.p_'+menu.list_cats[i]);
				}catch(e){}
			}
		}
		
		menu.closeAll = function(){
			for(i=0;i< menu.list_cats.length;i++){
				try{
					$('link_'+menu.list_cats[i]).innerHTML = eval('menu.p_'+menu.list_cats[i]);
				}catch(e){}
			
					//$('link_'+menu.list_cats[i]).innerHTML = eval('menu.p_'+menu.list_cats[i]);
			}
		}
		
		menu.sub_cat = function(cod){
				menu.closeAll();
				$('link_'+cod).innerHTML = eval('menu.p_'+cod) + eval('menu.cat_'+cod);
			//alert('menu.links_'+cod);				
			eval(eval('menu.links_'+cod));
		}
		
		menu.esportes = function(cod){
			//MENU ESPORTES
			if(cfe.cfei == '39' || cfe.cfei == 39 ){
				cfe.obj(3,39,'conteudo','esporte='+cod,0);
			}else{
				cfe.obj(3,39,'conteudo','esporte='+cod,0);
			}
			
		}
		
		menu.conteudo = function(cod){
			//MENU ESPORTES
			if(cfe.cfei == '31' || cfe.cfei == 31 ){
				cfe.obj(3,31,'conteudo','esporte='+cod,0);
			}else{
				cfe.init(3,31,'esporte='+cod);
			}
			
		} 
		menu.detalhes = function(){
			if(cfe.cfei == '32' || cfe.cfei == 32 ){
				cfe.obj(3,32,'conteudo','prod='+cod,0);
			}else{
				cfe.init(3,32,'prod='+cod);
			}
		}	

	busca.validate = function(){
		//a serialFunction:
		
				
		if($('str_busca').value == "" && $('marca_busca').value == ""){
			alert('É necessário usar no mínimo um critério de busca.');
			Field.focus('str_busca');
			return false;
		}else{
			
			return 'str_busca=' + $('str_busca').value + '&marca_busca=' + $('marca_busca').value;
		}
	}

	captBusca = function(e){
		if(e == 13){
			//alert(e);
			busca.validate();
		}
	}

cadastro.save = function(formulario){
	var valores, destino='', msg = '',posts='',focar='',prime='';
	
	valores = Form.getElements($('cada').name);
	
	valores.each( function(itemm){
			if(itemm.name == 'destinys'){
				destino = 'destino=' + itemm.value;
			}else{ //validar 
				if(itemm.name.substring(0,2) == "r_" && itemm.value == ''){ // eh requerido e nao foi digitado
					if(prime == '') prime = itemm;
					msg += itemm.id + ' - é necessário\n';
					if(focar == '') focar = itemm;
				}else if(itemm.name.substring(0,2) == "e_" ){//email
					if(itemm.value == ''){
						msg += itemm.id + ' - é necessário\n';	
						if(focar == '') focar = itemm;
					}else if(itemm.value.indexOf("@",1) == -1){
						msg += itemm.id + ' - precisa conter uma conta válida\n';
						if(focar == '') focar = itemm;
					}else{
						posts += itemm.name + '=' + itemm.value + "&";
					}
				}else if(itemm.name.substring(0,2) == "n_" ){// nao requerido
					posts += itemm.name + '=' + itemm.value + "&";
				}else{
					posts += itemm.name + '=' + itemm.value + "&";
				}
			}
		});	
	if(msg == ''){ // enviar:
		valores = Form.getElements($('cada').name);
		//alert('valores'+valores+ '------'+posts);
		cfe.cfejs_cfe('cadastro','form_save',posts);
		//$('botCad').innerHTML='<img src=../adm/presentation/images/loading2.gif>';
		//alert('enviar');
	}else{
		msg = 'Os campos abaixo precisam ser digitados:\n\n' + msg;
		alert(msg);	
		try{Field.focus(prime);	}catch(ee){}
	}
}

login.login_pag_bot = function(formulario,dest){
	var valores, destino='', msg = '',posts='',focar='',prime='';
	
	valores = Form.getElements($('login').name);
	//alert(valores);
	valores.each( function(itemm){
			if(itemm.name == 'destinys'){
				destino = 'destino=' + itemm.value;
			}else{ //validar 
				if(itemm.name.substring(0,2) == "r_" && itemm.value == ''){ // eh requerido e nao foi digitado
					if(prime == '') prime = itemm;
					msg += itemm.id + ' - é necessário\n';
					if(focar == '') focar = itemm;
				}else if(itemm.name.substring(0,2) == "e_" ){//email
					if(itemm.value == ''){
						msg += itemm.id + ' - é necessário\n';	
						if(focar == '') focar = itemm;
					}else if(itemm.value.indexOf("@",1) == -1){
						msg += itemm.id + ' - precisa conter uma conta válida\n';
						if(focar == '') focar = itemm;
					}else{
						posts += itemm.name + '=' + itemm.value + "&";
					}
				}else if(itemm.name.substring(0,2) == "n_" ){// nao requerido
					posts += itemm.name + '=' + itemm.value + "&";
				}else{
					posts += itemm.name + '=' + itemm.value + "&";
				}
			}
		});
	posts += 'dest=' + dest + "&";
	
	if(msg == ''){ // enviar:
		//valores = Form.getElements($('login').name);
		//alert('valores'+valores+ '------'+posts);
		cfe.cfejs_cfe('login','login_pag',posts);
  
		//alert('enviar');
	}else{
		msg = 'Os campos abaixo precisam ser digitados:\n\n' + msg;
		alert(msg);	
		try{Field.focus(prime);	}catch(ee){}
	}
}

login.login_topo = function(formulario){
	var valores, destino='', msg = '',posts='',focar='',prime='';
	
	valores = Form.getElements($('login_topo').name);
	
	valores.each( function(itemm){
			if(itemm.name == "email" || itemm.name == "senha" ){ 
				if(itemm.value == ""){
					if(prime == '') prime = itemm;
					msg += itemm.id + ' - é necessário\n';
					if(focar == '') focar = itemm;
				}else{
					posts += itemm.name + '=' + itemm.value + "&";
				}
			}
		});	
	if(msg == ''){ // enviar:
		cfe.cfejs_cfe('login','login_topo',posts + '&cfei=' + cfe.cfei);
  
		//alert('enviar');
	}else{
		msg = 'Os campos abaixo precisam ser digitados:\n\n' + msg;
		alert(msg);	
		try{Field.focus(prime);	}catch(ee){}
	}
}




pagamentos.cond = function(){
  jQuery('input').each(
  function(){
    if(this.type=="radio" && this.name=='pagamento') 
    if(this.checked ){
      if( !eval('pagamentos.'+this.value) ) {
        Effect.SlideDown('s'+this.value);
        eval('pagamentos.'+this.value+'=true;');
      }
    }else{
      if( eval('pagamentos.'+this.value) ) {
        Effect.SlideUp('s'+this.value);
        eval('pagamentos.'+this.value+'=false;');
      }
    }
	//else
	//alert(this.type);
}
);
}





pagamentos.mesmo = function(check,formulario){
	if(check){
		cfe.cfejs_cfe('pagamentos','mesmo','mesmo_E=true');
	}else{
		cfe.cfejs_cfe('pagamentos','mesmo','mesmo_E=false');	
	}
}

pagamentos.save = function(){
	//validação
	//alert('cjs:pagamentos.save');
	
	var entrega_check = false, valores, destino='', msg = '',posts='',focar='',prime='';
	valores = Form.getElements($('entrega').name);
	valores.each( function(itemm){
			if(itemm.name == 'destinys'){
				destino = 'destino=' + itemm.value;
			}else{ //validar 
				
				if(itemm.name.substring(0,2) == "r_" && itemm.value == ''){ // eh requerido e nao foi digitado
					if(prime == '') prime = itemm;
					msg += itemm.id + ' - é necessário\n';
					if(focar == '') focar = itemm;
				}else if(itemm.name.substring(0,2) == "e_" ){//email
					if(itemm.value == ''){
						msg += itemm.id + ' - é necessário\n';	
						if(focar == '') focar = itemm;
					}else if(itemm.value.indexOf("@",1) == -1){
						msg += itemm.id + ' - precisa conter uma conta válida\n';
						if(focar == '') focar = itemm;
					}else{
						posts += itemm.name + '=' + itemm.value + "&";
					}
				}else if(itemm.name.substring(0,2) == "n_" ){// nao requerido
					posts += itemm.name + '=' + itemm.value + "&";
				}else{
					posts += itemm.name + '=' + itemm.value + "&";
				}
			}
		});
			
	if(msg == ''){ // enviar:
		if($F('pag_tipo') == ''){
			alert('Por favor, selecione uma forma de pagamento clicando em cartão de crédito, cheque, boleto ou PagueSeguro.');
			try{Field.focus('pagamento');	}catch(ee){}
			entrega_check = false;
		}else{
			entrega_check = true;
		}
		
	}else{
		msg = 'Os campos abaixo precisam ser digitados:\n\n' + msg;
		alert(msg);	
		try{Field.focus(prime);	}catch(ee){}
	}
	if(entrega_check){
		//validar formas de pagamento:
		var msg2='',prime2='';
		if($F('pag_tipo') == 'cartao'){
			if($F('cartao') == ''){
				msg2 += '\nCartão - precisa ser selecionado.';
				if(prime2 == '') prime2 = 'cartao';
			}
			try{
			if($F('parcelamento') == ''){
				msg2 += '\nParcelamento - precisa ser selecionado.';
				if(prime2 == '') prime2 = 'parcelamento';
			}
			}catch(ee){}
			if($F('nome_cartao') == ''){
				msg2 += '\nNome do cartão - precisa ser digitado.';
				if(prime2 == '') prime2 = 'nome_cartao';
			}
			if($F('num_cartao') == ''){
				msg2 += '\nNúmero do cartão- precisa ser digitado.';
				if(prime2 == '') prime2 = 'num_cartao';
			}
			if($F('cod_verificador') == ''){
				msg2 += '\nCód verificados - precisa ser digitado.';
				if(prime2 == '') prime2 = 'cod_verificador';
			}
			if($F('mes_validade') == ''){
				msg2 += '\n Mês de validade - precisa ser selecionado.';
				if(prime2 == '') prime2 = 'mes_validade';
			}
			if($F('ano_validade') == ''){
				msg2 += '\nAno de validade - precisa ser selecionado.';
				if(prime2 == '') prime2 = 'ano_validade';
			}
			
		}else if($F('pag_tipo') == 'cheque'){
			if($F('banco') == ''){
				msg2 += '\nBanco - precisa ser informado.';
				if(prime2 == '') prime2 = 'banco';
			}
			try{
				if($F('parcelacheque') == ''){
					msg2 += '\nParcelamento - precisa ser selecionado.';
					if(prime2 == '') prime2 = 'parcelacheque';
				}else{
					var parc = Math.abs($F('parcelacheque'));
					var i;
					for(i=1;i<=parc;i++){
						if($F('cheque'+i) == ''){
							msg2 += '\nNúmero cheque '+i+' - precisa ser informado.';
							if(prime2 == '') prime2 = 'cheque'+i;
						}
					}
				}
			}catch(ee){}
			
		}else if($F('pag_tipo') == 'boleto'){
			msg2 = '';
		}
		if(msg2 != ''){
			alert('Os campos abaixo precisam ser digitados: \n\n' + msg2);
			try{Field.focus(prime2);	}catch(ee){}
		}else{
			posts = Form.serialize('entrega') + '&' + Form.serialize('pagamentosssssssss');
			cfe.cfejs_cfe('pagamentos','save',posts);
		}
	}
}

produto.indicar = function(prod){
	var valores, destino='', msg = '',posts='',focar='',prime='';
	var nome = $F('r_nome');
	var email = $F('e_email');
	var mensagem = $F('n_mensagem');
	var remetente = $F('n_remetente');
	var mailRemetente = $F('n_email_remetente');
	
	if(nome == ""){
		if(prime == '') prime = 'r_nome';
		msg = "\nnome do amigo - é necessário";
	}
	if(email == ""){
		if(prime == '') prime = 'e_email';
		msg += "\n email do amigo - é necessário";
	}
	if(mensagem == ""){
		if(prime == '') prime = 'n_mensagem';
		msg += "\n mensagem - é necessário";
	}

	posts += 'prodind=' + prod + " &";
	posts += 'nome=' + nome + "&";
	posts += 'email=' + email + "&";
	posts += 'mensagem=' + mensagem + "&";
	posts += 'remetente=' + remetente + "&";
	posts += 'mailremetente=' + mailRemetente + "&";
	
	posts += 'prod_ind=' + prod + "&";
	
	

	if(msg == ''){ // enviar:
		cfe.obj.div('indicar','produto','indicar_send',posts,0);
		
		//alert('enviar');
	}else{
		msg = 'Os campos abaixo precisam ser digitados:\n\n' + msg;
		alert(msg);	
		try{Field.focus(prime);	}catch(ee){}
	}
}




seusPedidos.recibo = function(pedido){
	$("seusPeds").action="../externas/emporioaventura/recibo.php";
	$("seusPeds").cod.value = pedido;
	$("seusPeds").cfe.value = cfe.cfe;
	$("seusPeds").method="post";
	$("seusPeds").submit();

}

seusPedidos.rastreamento = function(rastreamento){
	if(rastreamento == ""){
		alert("Infelizmente o código de rastreamento ainda não está disponível, qualquer dúvida por favor entre em contato conosco para esclarecermos a situação.");
	}else{
		window.open("http://websro.correios.com.br/sro_bin/txect01$.QueryList?P_LINGUA=001&P_TIPO=001&P_COD_UNI=" + rastreamento);
	}
}


pagamentos.cond = function(){
  jQuery('input').each(
  function(){
    if(this.type=="radio" && this.name=='pagamento') 
    if(this.checked ){
      if( !eval('pagamentos.'+this.value) ) {
        Effect.SlideDown('s'+this.value);
        eval('pagamentos.'+this.value+'=true;');
      }
    }else{
      if( eval('pagamentos.'+this.value) ) {
        Effect.SlideUp('s'+this.value);
        eval('pagamentos.'+this.value+'=false;');
      }
    }
	//else
	//alert(this.type);
}
);
}





pagamentos.mesmo = function(check,formulario){
	if(check){
		cfe.cfejs_cfe('pagamentos','mesmo','mesmo_E=true');
	}else{
		cfe.cfejs_cfe('pagamentos','mesmo','mesmo_E=false');	
	}
}

pagamentos.save = function(){
	//validação
	//alert('cjs:pagamentos.save');
	
	var entrega_check = false, valores, destino='', msg = '',posts='',focar='',prime='';
	valores = Form.getElements($('entrega').name);
	valores.each( function(itemm){
			if(itemm.name == 'destinys'){
				destino = 'destino=' + itemm.value;
			}else{ //validar 
				
				if(itemm.name.substring(0,2) == "r_" && itemm.value == ''){ // eh requerido e nao foi digitado
					if(prime == '') prime = itemm;
					msg += itemm.id + ' - é necessário\n';
					if(focar == '') focar = itemm;
				}else if(itemm.name.substring(0,2) == "e_" ){//email
					if(itemm.value == ''){
						msg += itemm.id + ' - é necessário\n';	
						if(focar == '') focar = itemm;
					}else if(itemm.value.indexOf("@",1) == -1){
						msg += itemm.id + ' - precisa conter uma conta válida\n';
						if(focar == '') focar = itemm;
					}else{
						posts += itemm.name + '=' + itemm.value + "&";
					}
				}else if(itemm.name.substring(0,2) == "n_" ){// nao requerido
					posts += itemm.name + '=' + itemm.value + "&";
				}else{
					posts += itemm.name + '=' + itemm.value + "&";
				}
			}
		});
			
	if(msg == ''){ // enviar:
		if($F('pag_tipo') == ''){
			alert('Por favor, selecione uma forma de pagamento clicando em cartão de crédito, cheque, boleto ou PagueSeguro.');
			try{Field.focus('pagamento');	}catch(ee){}
			entrega_check = false;
		}else{
			entrega_check = true;
		}
		
	}else{
		msg = 'Os campos abaixo precisam ser digitados:\n\n' + msg;
		alert(msg);	
		try{Field.focus(prime);	}catch(ee){}
	}
	if(entrega_check){
		//validar formas de pagamento:
		var msg2='',prime2='';
		if($F('pag_tipo') == 'cartao'){
			if($F('cartao') == ''){
				msg2 += '\nCartão - precisa ser selecionado.';
				if(prime2 == '') prime2 = 'cartao';
			}
			try{
			if($F('parcelamento') == ''){
				msg2 += '\nParcelamento - precisa ser selecionado.';
				if(prime2 == '') prime2 = 'parcelamento';
			}
			}catch(ee){}
			if($F('nome_cartao') == ''){
				msg2 += '\nNome do cartão - precisa ser digitado.';
				if(prime2 == '') prime2 = 'nome_cartao';
			}
			if($F('num_cartao') == ''){
				msg2 += '\nNúmero do cartão- precisa ser digitado.';
				if(prime2 == '') prime2 = 'num_cartao';
			}
			if($F('cod_verificador') == ''){
				msg2 += '\nCód verificados - precisa ser digitado.';
				if(prime2 == '') prime2 = 'cod_verificador';
			}
			if($F('mes_validade') == ''){
				msg2 += '\n Mês de validade - precisa ser selecionado.';
				if(prime2 == '') prime2 = 'mes_validade';
			}
			if($F('ano_validade') == ''){
				msg2 += '\nAno de validade - precisa ser selecionado.';
				if(prime2 == '') prime2 = 'ano_validade';
			}
			
		}else if($F('pag_tipo') == 'cheque'){
			if($F('banco') == ''){
				msg2 += '\nBanco - precisa ser informado.';
				if(prime2 == '') prime2 = 'banco';
			}
			try{
				if($F('parcelacheque') == ''){
					msg2 += '\nParcelamento - precisa ser selecionado.';
					if(prime2 == '') prime2 = 'parcelacheque';
				}else{
					var parc = Math.abs($F('parcelacheque'));
					var i;
					for(i=1;i<=parc;i++){
						if($F('cheque'+i) == ''){
							msg2 += '\nNúmero cheque '+i+' - precisa ser informado.';
							if(prime2 == '') prime2 = 'cheque'+i;
						}
					}
				}
			}catch(ee){}
			
		}else if($F('pag_tipo') == 'boleto'){
			msg2 = '';
		}
		if(msg2 != ''){
			alert('Os campos abaixo precisam ser digitados: \n\n' + msg2);
			try{Field.focus(prime2);	}catch(ee){}
		}else{
			posts = Form.serialize('entrega') + '&' + Form.serialize('pagamentosssssssss');
			cfe.cfejs_cfe('pagamentos','save',posts);
		}
	}
}


	pagSeguro.save = function(){

	var valores, destino="", msg = "",posts="",focar="",prime="";
	
	valores = Form.getElements($("pagSeguro").name);

	valores.each( function(itemm){
			if(itemm.name == "destinys"){
				destino = "destino=" + itemm.value;
			}else{ //validar 
				if(itemm.name.substring(0,2) == "r_" && itemm.value == ""){ // eh requerido e nao foi digitado
					if(prime == "") prime = itemm;
					msg += itemm.id + " , ";
					if(focar == "") focar = itemm;
					
				}else if(itemm.name.substring(0,2) == "e_" ){//email
					if(itemm.value == ""){
						msg += itemm.id + " , ";	
						if(focar == "") focar = itemm;
					}else if(itemm.value.indexOf("@",1) == -1){
						msg += itemm.id + " (inválido), ";
						if(focar == "") focar = itemm;
					}else{
						posts += itemm.name + "=" + cfe.escapeSpecial(itemm.value) + "&";
					}
				}else if(itemm.name.substring(0,2) == "n_" ){// nao requerido
					posts += itemm.name + "=" + cfe.escapeSpecial(itemm.value) + "&";
				}else{
					posts += itemm.name + "=" + cfe.escapeSpecial(itemm.value) + "&";
				}
			}
		});
			
	if(msg == ""){ // enviar:
		cfe.cfejs_cfe("pagSeguro","form_save",posts);
		//Form.reset($("pagSeguro").name);
		cfe.prompt("sucess");
	}else{
		msg = "<div align=left> Os campos abaixo precisam ser digitados:\n\n" + msg + "</div>";
		cfe.prompt(msg);	
		try{Field.focus(prime);	}catch(ee){}
	}
	
}		
		



jQuery(document).ready(function(){
 


calFrete = function(){ 
  var Val,cep ;

  cep = eval('$(\'cep\').value');
	if(cep == ''){
	alert('Digite o CEP para calcular o frete.'); return false;
	}

  jQuery('input:radio').each(function(){ 
    if ( jQuery(this).is(':checked') && this.id=='selecionado' ) {
		Val = this.value;
	}else{}
  });
  cfe.cfejs_cfe('carrinho','getfrete','cep='+cep +'&selecionado='+Val);
}

 
 });



jQuery(document).ready(function(){
 
calFreteP = function(){ 
  var Val,cep ;

	cep = $('CEP').value;
 
	if(cep == ''){
	alert('Digite o CEP para calcular o frete.'); return false;
	}

  jQuery('input:radio').each(function(){ 
    if ( jQuery(this).is(':checked') && this.id=='selecionado' ) {
		Val = this.value;
	}else{}
  });
  cfe.cfejs_cfe('carrinho','getfreteP','cep='+cep +'&selecionado='+Val);
}

 
 });


/* Copyright (c) 2009 Kelvin Luck (kelvin AT kelvinluck DOT com || http://www.kelvinluck.com)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 * 
 * See http://kelvinluck.com/assets/jquery/jScrollPane/
 * jQueryId: jScrollPane.js 87 2009-10-12 10:44:17Z kelvin.luck jQuery
 */

/**
 * Replace the vertical scroll bars on any matched elements with a fancy
 * styleable (via CSS) version. With JS disabled the elements will
 * gracefully degrade to the browsers own implementation of overflow:auto.
 * If the mousewheel plugin has been included on the page then the scrollable areas will also
 * respond to the mouse wheel.
 *
 * @example jQuery(".scroll-pane").jScrollPane();
 *
 * @name jScrollPane
 * @type jQuery
 * @param Object	settings	hash with options, described below.
 *								scrollbarWidth	-	The width of the generated scrollbar in pixels
 *								scrollbarMargin	-	The amount of space to leave on the side of the scrollbar in pixels
 *								wheelSpeed		-	The speed the pane will scroll in response to the mouse wheel in pixels
 *								showArrows		-	Whether to display arrows for the user to scroll with
 *								arrowSize		-	The height of the arrow buttons if showArrows=true
 *								animateTo		-	Whether to animate when calling scrollTo and scrollBy
 *								dragMinHeight	-	The minimum height to allow the drag bar to be
 *								dragMaxHeight	-	The maximum height to allow the drag bar to be
 *								animateInterval	-	The interval in milliseconds to update an animating scrollPane (default 100)
 *								animateStep		-	The amount to divide the remaining scroll distance by when animating (default 3)
 *								maintainPosition-	Whether you want the contents of the scroll pane to maintain it's position when you re-initialise it - so it doesn't scroll as you add more content (default true)
 *								tabIndex		-	The tabindex for this jScrollPane to control when it is tabbed to when navigating via keyboard (default 0)
 *								enableKeyboardNavigation - Whether to allow keyboard scrolling of this jScrollPane when it is focused (default true)
 *								animateToInternalLinks - Whether the move to an internal link (e.g. when it's focused by tabbing or by a hash change in the URL) should be animated or instant (default false)
 *								scrollbarOnLeft	-	Display the scrollbar on the left side? (needs stylesheet changes, see examples.html)
 *								reinitialiseOnImageLoad - Whether the jScrollPane should automatically re-initialise itself when any contained images are loaded (default false)
 *								topCapHeight	-	The height of the "cap" area between the top of the jScrollPane and the top of the track/ buttons
 *								bottomCapHeight	-	The height of the "cap" area between the bottom of the jScrollPane and the bottom of the track/ buttons
 * @return jQuery
 * @cat Plugins/jScrollPane
 * @author Kelvin Luck (kelvin AT kelvinluck DOT com || http://www.kelvinluck.com)
 */

(function(jQuery) {

jQuery.jScrollPane = {
	active : []
};
jQuery.fn.jScrollPane = function(settings)
{
	settings = jQuery.extend({}, jQuery.fn.jScrollPane.defaults, settings);

	var rf = function() { return false; };
	
	return this.each(
		function()
		{
			var jQuerythis = jQuery(this);
			var paneEle = this;
			var currentScrollPosition = 0;
			var paneWidth;
			var paneHeight;
			var trackHeight;
			var trackOffset = settings.topCapHeight;
			
			if (jQuery(this).parent().is('.jScrollPaneContainer')) {
				currentScrollPosition = settings.maintainPosition ? jQuerythis.position().top : 0;
				var jQueryc = jQuery(this).parent();
				paneWidth = jQueryc.innerWidth();
				paneHeight = jQueryc.outerHeight();
				jQuery('>.jScrollPaneTrack, >.jScrollArrowUp, >.jScrollArrowDown, >.jScrollCap', jQueryc).remove();
				jQuerythis.css({'top':0});
			} else {
				jQuerythis.data('originalStyleTag', jQuerythis.attr('style'));
				// Switch the element's overflow to hidden to ensure we get the size of the element without the scrollbars [http://plugins.jquery.com/node/1208]
				jQuerythis.css('overflow', 'hidden');
				this.originalPadding = jQuerythis.css('paddingTop') + ' ' + jQuerythis.css('paddingRight') + ' ' + jQuerythis.css('paddingBottom') + ' ' + jQuerythis.css('paddingLeft');
				this.originalSidePaddingTotal = (parseInt(jQuerythis.css('paddingLeft')) || 0) + (parseInt(jQuerythis.css('paddingRight')) || 0);
				paneWidth = jQuerythis.innerWidth();
				paneHeight = jQuerythis.innerHeight();
				var jQuerycontainer = jQuery('<div></div>')
					.attr({'className':'jScrollPaneContainer'})
					.css(
						{
							'height':paneHeight+'px', 
							'width':paneWidth+'px'
						}
					);
				if (settings.enableKeyboardNavigation) {
					jQuerycontainer.attr(
						'tabindex', 
						settings.tabIndex
					);
				}
				jQuerythis.wrap(jQuerycontainer);
				// deal with text size changes (if the jquery.em plugin is included)
				// and re-initialise the scrollPane so the track maintains the
				// correct size
				jQuery(document).bind(
					'emchange', 
					function(e, cur, prev)
					{
						jQuerythis.jScrollPane(settings);
					}
				);
				
			}
			trackHeight = paneHeight;
			
			if (settings.reinitialiseOnImageLoad) {
				// code inspired by jquery.onImagesLoad: http://plugins.jquery.com/project/onImagesLoad
				// except we re-initialise the scroll pane when each image loads so that the scroll pane is always up to size...
				// TODO: Do I even need to store it in jQuery.data? Is a local variable here the same since I don't pass the reinitialiseOnImageLoad when I re-initialise?
				var jQueryimagesToLoad = jQuery.data(paneEle, 'jScrollPaneImagesToLoad') || jQuery('img', jQuerythis);
				var loadedImages = [];
				
				if (jQueryimagesToLoad.length) {
					jQueryimagesToLoad.each(function(i, val)	{
						jQuery(this).bind('load readystatechange', function() {
							if(jQuery.inArray(i, loadedImages) == -1){ //don't double count images
								loadedImages.push(val); //keep a record of images we've seen
								jQueryimagesToLoad = jQuery.grep(jQueryimagesToLoad, function(n, i) {
									return n != val;
								});
								jQuery.data(paneEle, 'jScrollPaneImagesToLoad', jQueryimagesToLoad);
								var s2 = jQuery.extend(settings, {reinitialiseOnImageLoad:false});
								jQuerythis.jScrollPane(s2); // re-initialise
							}
						}).each(function(i, val) {
							if(this.complete || this.complete===undefined) { 
								//needed for potential cached images
								this.src = this.src; 
							} 
						});
					});
				};
			}

			var p = this.originalSidePaddingTotal;
			var realPaneWidth = paneWidth - settings.scrollbarWidth - settings.scrollbarMargin - p;

			var cssToApply = {
				'height':'auto',
				'width': realPaneWidth + 'px'
			}

			if(settings.scrollbarOnLeft) {
				cssToApply.paddingLeft = settings.scrollbarMargin + settings.scrollbarWidth + 'px';
			} else {
				cssToApply.paddingRight = settings.scrollbarMargin + 'px';
			}

			jQuerythis.css(cssToApply);

			var contentHeight = jQuerythis.outerHeight();
			var percentInView = paneHeight / contentHeight;

			if (percentInView < .99) {
				var jQuerycontainer = jQuerythis.parent();
				jQuerycontainer.append(
					jQuery('<div></div>').addClass('jScrollCap jScrollCapTop').css({height:settings.topCapHeight}),
					jQuery('<div></div>').attr({'className':'jScrollPaneTrack'}).css({'width':settings.scrollbarWidth+'px'}).append(
						jQuery('<div></div>').attr({'className':'jScrollPaneDrag'}).css({'width':settings.scrollbarWidth+'px'}).append(
							jQuery('<div></div>').attr({'className':'jScrollPaneDragTop'}).css({'width':settings.scrollbarWidth+'px'}),
							jQuery('<div></div>').attr({'className':'jScrollPaneDragBottom'}).css({'width':settings.scrollbarWidth+'px'})
						)
					),
					jQuery('<div></div>').addClass('jScrollCap jScrollCapBottom').css({height:settings.bottomCapHeight})
				);
				
				var jQuerytrack = jQuery('>.jScrollPaneTrack', jQuerycontainer);
				var jQuerydrag = jQuery('>.jScrollPaneTrack .jScrollPaneDrag', jQuerycontainer);
				
				
				var currentArrowDirection;
				var currentArrowTimerArr = [];// Array is used to store timers since they can stack up when dealing with keyboard events. This ensures all timers are cleaned up in the end, preventing an acceleration bug.
				var currentArrowInc;
				var whileArrowButtonDown = function() 
				{
					if (currentArrowInc > 4 || currentArrowInc % 4 == 0) {
						positionDrag(dragPosition + currentArrowDirection * mouseWheelMultiplier);
					}
					currentArrowInc++;
				};

				if (settings.enableKeyboardNavigation) {
					jQuerycontainer.bind(
						'keydown.jscrollpane',
						function(e) 
						{
							switch (e.keyCode) {
								case 38: //up
									currentArrowDirection = -1;
									currentArrowInc = 0;
									whileArrowButtonDown();
									currentArrowTimerArr[currentArrowTimerArr.length] = setInterval(whileArrowButtonDown, 100);
									return false;
								case 40: //down
									currentArrowDirection = 1;
									currentArrowInc = 0;
									whileArrowButtonDown();
									currentArrowTimerArr[currentArrowTimerArr.length] = setInterval(whileArrowButtonDown, 100);
									return false;
								case 33: // page up
								case 34: // page down
									// TODO
									return false;
								default:
							}
						}
					).bind(
						'keyup.jscrollpane',
						function(e) 
						{
							if (e.keyCode == 38 || e.keyCode == 40) {
								for (var i = 0; i < currentArrowTimerArr.length; i++) {
									clearInterval(currentArrowTimerArr[i]);
								}
								return false;
							}
						}
					);
				}

				if (settings.showArrows) {
					
					var currentArrowButton;
					var currentArrowInterval;

					var onArrowMouseUp = function(event)
					{
						jQuery('html').unbind('mouseup', onArrowMouseUp);
						currentArrowButton.removeClass('jScrollActiveArrowButton');
						clearInterval(currentArrowInterval);
					};
					var onArrowMouseDown = function() {
						jQuery('html').bind('mouseup', onArrowMouseUp);
						currentArrowButton.addClass('jScrollActiveArrowButton');
						currentArrowInc = 0;
						whileArrowButtonDown();
						currentArrowInterval = setInterval(whileArrowButtonDown, 100);
					};
					jQuerycontainer
						.append(
							jQuery('<a></a>')
								.attr(
									{
										'href':'javascript:;', 
										'className':'jScrollArrowUp', 
										'tabindex':-1
									}
								)
								.css(
									{
										'width':settings.scrollbarWidth+'px',
										'top':settings.topCapHeight + 'px'
									}
								)
								.html('Scroll up')
								.bind('mousedown', function()
								{
									currentArrowButton = jQuery(this);
									currentArrowDirection = -1;
									onArrowMouseDown();
									this.blur();
									return false;
								})
								.bind('click', rf),
							jQuery('<a></a>')
								.attr(
									{
										'href':'javascript:;', 
										'className':'jScrollArrowDown', 
										'tabindex':-1
									}
								)
								.css(
									{
										'width':settings.scrollbarWidth+'px',
										'bottom':settings.bottomCapHeight + 'px'
									}
								)
								.html('Scroll down')
								.bind('mousedown', function()
								{
									currentArrowButton = jQuery(this);
									currentArrowDirection = 1;
									onArrowMouseDown();
									this.blur();
									return false;
								})
								.bind('click', rf)
						);
					var jQueryupArrow = jQuery('>.jScrollArrowUp', jQuerycontainer);
					var jQuerydownArrow = jQuery('>.jScrollArrowDown', jQuerycontainer);
				}
				
				if (settings.arrowSize) {
					trackHeight = paneHeight - settings.arrowSize - settings.arrowSize;
					trackOffset += settings.arrowSize;
				} else if (jQueryupArrow) {
					var topArrowHeight = jQueryupArrow.height();
					settings.arrowSize = topArrowHeight;
					trackHeight = paneHeight - topArrowHeight - jQuerydownArrow.height();
					trackOffset += topArrowHeight;
				}
				trackHeight -= settings.topCapHeight + settings.bottomCapHeight;
				jQuerytrack.css({'height': trackHeight+'px', top:trackOffset+'px'})
				
				var jQuerypane = jQuery(this).css({'position':'absolute', 'overflow':'visible'});
				
				var currentOffset;
				var maxY;
				var mouseWheelMultiplier;
				// store this in a seperate variable so we can keep track more accurately than just updating the css property..
				var dragPosition = 0;
				var dragMiddle = percentInView*paneHeight/2;
				
				// pos function borrowed from tooltip plugin and adapted...
				var getPos = function (event, c) {
					var p = c == 'X' ? 'Left' : 'Top';
					return event['page' + c] || (event['client' + c] + (document.documentElement['scroll' + p] || document.body['scroll' + p])) || 0;
				};
				
				var ignoreNativeDrag = function() {	return false; };
				
				var initDrag = function()
				{
					ceaseAnimation();
					currentOffset = jQuerydrag.offset(false);
					currentOffset.top -= dragPosition;
					maxY = trackHeight - jQuerydrag[0].offsetHeight;
					mouseWheelMultiplier = 2 * settings.wheelSpeed * maxY / contentHeight;
				};
				
				var onStartDrag = function(event)
				{
					initDrag();
					dragMiddle = getPos(event, 'Y') - dragPosition - currentOffset.top;
					jQuery('html').bind('mouseup', onStopDrag).bind('mousemove', updateScroll);
					if (jQuery.browser.msie) {
						jQuery('html').bind('dragstart', ignoreNativeDrag).bind('selectstart', ignoreNativeDrag);
					}
					return false;
				};
				var onStopDrag = function()
				{
					jQuery('html').unbind('mouseup', onStopDrag).unbind('mousemove', updateScroll);
					dragMiddle = percentInView*paneHeight/2;
					if (jQuery.browser.msie) {
						jQuery('html').unbind('dragstart', ignoreNativeDrag).unbind('selectstart', ignoreNativeDrag);
					}
				};
				var positionDrag = function(destY)
				{
					jQuerycontainer.scrollTop(0);
					destY = destY < 0 ? 0 : (destY > maxY ? maxY : destY);
					dragPosition = destY;
					jQuerydrag.css({'top':destY+'px'});
					var p = destY / maxY;
					jQuerythis.data('jScrollPanePosition', (paneHeight-contentHeight)*-p);
					jQuerypane.css({'top':((paneHeight-contentHeight)*p) + 'px'});
					jQuerythis.trigger('scroll');
					if (settings.showArrows) {
						jQueryupArrow[destY == 0 ? 'addClass' : 'removeClass']('disabled');
						jQuerydownArrow[destY == maxY ? 'addClass' : 'removeClass']('disabled');
					}
				};
				var updateScroll = function(e)
				{
					positionDrag(getPos(e, 'Y') - currentOffset.top - dragMiddle);
				};
				
				var dragH = Math.max(Math.min(percentInView*(paneHeight-settings.arrowSize*2), settings.dragMaxHeight), settings.dragMinHeight);
				
				jQuerydrag.css(
					{'height':dragH+'px'}
				).bind('mousedown', onStartDrag);
				
				var trackScrollInterval;
				var trackScrollInc;
				var trackScrollMousePos;
				var doTrackScroll = function()
				{
					if (trackScrollInc > 8 || trackScrollInc%4==0) {
						positionDrag((dragPosition - ((dragPosition - trackScrollMousePos) / 2)));
					}
					trackScrollInc ++;
				};
				var onStopTrackClick = function()
				{
					clearInterval(trackScrollInterval);
					jQuery('html').unbind('mouseup', onStopTrackClick).unbind('mousemove', onTrackMouseMove);
				};
				var onTrackMouseMove = function(event)
				{
					trackScrollMousePos = getPos(event, 'Y') - currentOffset.top - dragMiddle;
				};
				var onTrackClick = function(event)
				{
					initDrag();
					onTrackMouseMove(event);
					trackScrollInc = 0;
					jQuery('html').bind('mouseup', onStopTrackClick).bind('mousemove', onTrackMouseMove);
					trackScrollInterval = setInterval(doTrackScroll, 100);
					doTrackScroll();
					return false;
				};
				
				jQuerytrack.bind('mousedown', onTrackClick);
				
				jQuerycontainer.bind(
					'mousewheel',
					function (event, delta) {
						delta = delta || (event.wheelDelta ? event.wheelDelta / 120 : (event.detail) ?
-event.detail/3 : 0);
						initDrag();
						ceaseAnimation();
						var d = dragPosition;
						positionDrag(dragPosition - delta * mouseWheelMultiplier);
						var dragOccured = d != dragPosition;
						return !dragOccured;
					}
				);

				var _animateToPosition;
				var _animateToInterval;
				function animateToPosition()
				{
					var diff = (_animateToPosition - dragPosition) / settings.animateStep;
					if (diff > 1 || diff < -1) {
						positionDrag(dragPosition + diff);
					} else {
						positionDrag(_animateToPosition);
						ceaseAnimation();
					}
				}
				var ceaseAnimation = function()
				{
					if (_animateToInterval) {
						clearInterval(_animateToInterval);
						delete _animateToPosition;
					}
				};
				var scrollTo = function(pos, preventAni)
				{
					if (typeof pos == "string") {
						jQuerye = jQuery(pos, jQuerythis);
						if (!jQuerye.length) return;
						pos = jQuerye.offset().top - jQuerythis.offset().top;
					}
					ceaseAnimation();
					var maxScroll = contentHeight - paneHeight;
					pos = pos > maxScroll ? maxScroll : pos;
					jQuerythis.data('jScrollPaneMaxScroll', maxScroll);
					var destDragPosition = pos/maxScroll * maxY;
					if (preventAni || !settings.animateTo) {
						positionDrag(destDragPosition);
					} else {
						jQuerycontainer.scrollTop(0);
						_animateToPosition = destDragPosition;
						_animateToInterval = setInterval(animateToPosition, settings.animateInterval);
					}
				};
				jQuerythis[0].scrollTo = scrollTo;
				
				jQuerythis[0].scrollBy = function(delta)
				{
					var currentPos = -parseInt(jQuerypane.css('top')) || 0;
					scrollTo(currentPos + delta);
				};
				
				initDrag();
				
				scrollTo(-currentScrollPosition, true);
			
				// Deal with it when the user tabs to a link or form element within this scrollpane
				jQuery('*', this).bind(
					'focus',
					function(event)
					{
						var jQuerye = jQuery(this);
						
						// loop through parents adding the offset top of any elements that are relatively positioned between
						// the focused element and the jScrollPaneContainer so we can get the true distance from the top
						// of the focused element to the top of the scrollpane...
						var eleTop = 0;
						
						while (jQuerye[0] != jQuerythis[0]) {
							eleTop += jQuerye.position().top;
							jQuerye = jQuerye.offsetParent();
						}
						
						var viewportTop = -parseInt(jQuerypane.css('top')) || 0;
						var maxVisibleEleTop = viewportTop + paneHeight;
						var eleInView = eleTop > viewportTop && eleTop < maxVisibleEleTop;
						if (!eleInView) {
							var destPos = eleTop - settings.scrollbarMargin;
							if (eleTop > viewportTop) { // element is below viewport - scroll so it is at bottom.
								destPos += jQuery(this).height() + 15 + settings.scrollbarMargin - paneHeight;
							}
							scrollTo(destPos);
						}
					}
				)
				
				
				if (location.hash && location.hash.length > 1) {
					setTimeout(function() {scrollTo(location.hash);}, jQuery.browser.safari ? 100 : 0);
				}
				
				// use event delegation to listen for all clicks on links and hijack them if they are links to
				// anchors within our content...
				jQuery(document).bind(
					'click',
					function(e)
					{
						jQuerytarget = jQuery(e.target);
						if (jQuerytarget.is('a')) {
							var h = jQuerytarget.attr('href');
							if (h && h.substr(0, 1) == '#' && h.length > 1) {
								setTimeout(function() {scrollTo(h, !settings.animateToInternalLinks);}, jQuery.browser.safari ? 100 : 0);
							}
						}
					}
				); 
				
				// Deal with dragging and selecting text to make the scrollpane scroll...
				function onSelectScrollMouseDown(e)
				{
				  jQuery(document).bind('mousemove.jScrollPaneDragging', onTextSelectionScrollMouseMove);
				  jQuery(document).bind('mouseup.jScrollPaneDragging',  onSelectScrollMouseUp);
				 
				}
				
				var textDragDistanceAway;
				var textSelectionInterval;
				
				function onTextSelectionInterval()
				{
					direction = textDragDistanceAway < 0 ? -1 : 1;
					jQuerythis[0].scrollBy(textDragDistanceAway / 2);
				}

				function clearTextSelectionInterval()
				{
					if (textSelectionInterval) {
						clearInterval(textSelectionInterval);
						textSelectionInterval = undefined;
					}
				}
				
				function onTextSelectionScrollMouseMove(e)
				{
					var offset = jQuerythis.parent().offset().top;
					var maxOffset = offset + paneHeight;
					var mouseOffset = getPos(e, 'Y');
					textDragDistanceAway = mouseOffset < offset ? mouseOffset - offset : (mouseOffset > maxOffset ? mouseOffset - maxOffset : 0);
					if (textDragDistanceAway == 0) {
						clearTextSelectionInterval();
					} else {
						if (!textSelectionInterval) {
							textSelectionInterval = setInterval(onTextSelectionInterval, 100);
						}
					}
				}

				function onSelectScrollMouseUp(e)
				{
				  jQuery(document)
					 .unbind('mousemove.jScrollPaneDragging')
					 .unbind('mouseup.jScrollPaneDragging');
				  clearTextSelectionInterval();
				}

				jQuerycontainer.bind('mousedown.jScrollPane', onSelectScrollMouseDown);

				
				jQuery.jScrollPane.active.push(jQuerythis[0]);
				
			} else {
				jQuerythis.css(
					{
						'height':paneHeight+'px',
						'width':paneWidth-this.originalSidePaddingTotal+'px',
						'padding':this.originalPadding
					}
				);
				jQuerythis[0].scrollTo = jQuerythis[0].scrollBy = function() {};
				// clean up listeners
				jQuerythis.parent().unbind('mousewheel').unbind('mousedown.jScrollPane').unbind('keydown.jscrollpane').unbind('keyup.jscrollpane');
			}
			
		}
	)
};

jQuery.fn.jScrollPaneRemove = function()
{
	jQuery(this).each(function()
	{
		jQuerythis = jQuery(this);
		var jQueryc = jQuerythis.parent();
		if (jQueryc.is('.jScrollPaneContainer')) {
			jQuerythis.css(
				{
					'top':'',
					'height':'',
					'width':'',
					'padding':'',
					'overflow':'',
					'position':''
				}
			);
			jQuerythis.attr('style', jQuerythis.data('originalStyleTag'));
			jQueryc.after(jQuerythis).remove();
		}
	});
}

jQuery.fn.jScrollPane.defaults = {
	scrollbarWidth : 10,
	scrollbarMargin : 5,
	wheelSpeed : 18,
	showArrows : false,
	arrowSize : 0,
	animateTo : false,
	dragMinHeight : 1,
	dragMaxHeight : 99999,
	animateInterval : 100,
	animateStep: 3,
	maintainPosition: true,
	scrollbarOnLeft: false,
	reinitialiseOnImageLoad: false,
	tabIndex : 0,
	enableKeyboardNavigation: true,
	animateToInternalLinks: false,
	topCapHeight: 0,
	bottomCapHeight: 0
};

// clean up the scrollTo expandos
jQuery(window)
	.bind('unload', function() {
		var els = jQuery.jScrollPane.active; 
		for (var i=0; i<els.length; i++) {
			els[i].scrollTo = els[i].scrollBy = null;
		}
	}
);

})(jQuery);

		
	var par = '';

	//cfe.init(72,750,par);
	
		
	